If you know, that your results implements a certain interface you could use the interface as datatype:
public void LogEmployees<T>(IEnumerable<T> list)
{
foreach (T item in list)
{
}
}
It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.
Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.
I guess
List<T> CreateEmptyGenericList<T>(T example) {
return new List<T>();
}
void something() {
var o = new { Id = 1, Name = "foo" };
var emptyListOfAnonymousType = CreateEmptyGenericList(o);
}
will work.
You might also consider writing it like this:
void something() {
var String = string.Emtpy;
var Integer = int.MinValue;
var emptyListOfAnonymousType = CreateEmptyGenericList(new { Id = Integer, Name = String });
}
Now with local functions especially, but you could always do it by passing a delegate that makes the anonymous type.
So if your goal was to run different logic on the same sources, and be able to combine the results into a single list. Not sure what nuance this is missing to meet the stated goal, but as long as you return a T
and pass a delegate to make T
, you can return an anonymous type from a function.
// returning an anonymous type
// look mom no casting
void LookMyChildReturnsAnAnonICanConsume()
{
// if C# had first class functions you could do
// var anonyFunc = (name:string,id:int) => new {Name=name,Id=id};
var items = new[] { new { Item1 = "hello", Item2 = 3 } };
var itemsProjection =items.Select(x => SomeLogic(x.Item1, x.Item2, (y, i) => new { Word = y, Count = i} ));
// same projection = same type
var otherSourceProjection = SomeOtherSource((y,i) => new {Word=y,Count=i});
var q =
from anony1 in itemsProjection
join anony2 in otherSourceProjection
on anony1.Word equals anony2.Word
select new {anony1.Word,Source1Count=anony1.Count,Source2Count=anony2.Count};
var togetherForever = itemsProjection.Concat(otherSourceProjection).ToList();
}
T SomeLogic<T>(string item1, int item2, Func<string,int,T> f){
return f(item1,item2);
}
IEnumerable<T> SomeOtherSource<T>(Func<string,int,T> f){
var dbValues = new []{Tuple.Create("hello",1), Tuple.Create("bye",2)};
foreach(var x in dbValues)
yield return f(x.Item1,x.Item2);
}
Assuming you are using this for a web service, you can just apply the following attribute to the class:
[System.Web.Script.Services.ScriptService]
Then the following attribute to each method that should return Json:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
And set the return type for the methods to be "object"
No; an anonymous type can't be made to do anything except have a few properties. You will need to create your own type. I didn't read the linked article in depth, but it looks like it uses Reflection.Emit to create new types on the fly; but if you limit discussion to things within C# itself you can't do what you want.
If you're storing the object as type object
, you need to use reflection. This is true of any object type, anonymous or otherwise. On an object o, you can get its type:
Type t = o.GetType();
Then from that you look up a property:
PropertyInfo p = t.GetProperty("Foo");
Then from that you can get a value:
object v = p.GetValue(o, null);
This answer is long overdue for an update for C# 4:
dynamic d = o;
object v = d.Foo;
And now another alternative in C# 6:
object v = o?.GetType().GetProperty("Foo")?.GetValue(o, null);
Note that by using ?.
we cause the resulting v
to be null
in three different situations!
o
is null
, so there is no object at allo
is non-null
but doesn't have a property Foo
o
has a property Foo
but its real value happens to be null
.So this is not equivalent to the earlier examples, but may make sense if you want to treat all three cases the same.
Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic
.
Now, if you were to use an ExpandoObject and reference it through a dynamic
variable, you could add or remove fields on the fly.
edit
Sure you can: just cast it to IDictionary<string, object>
. Then you can use the indexer.
You use the same casting technique to iterate over the fields:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
foreach (var property in (IDictionary<string, object>)employee)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33
The above code and more can be found by clicking on that link.
The essence is this:
This works for me:
var new_item = $('<p>hello</p>').hide();
parent.append(new_item);
new_item.show('normal');
or:
$('<p>hello</p>').hide().appendTo(parent).show('normal');
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
There is a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array does not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to its inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
What follows is an example using a callback to process the files in a directory tree. This is an initial validation pass which just counts the files to process and ensure none exceed a predetermined maximum size. In this case we just create the callback inline with the API invocation. However, we reflect the target method out as a static value so that the reflection is not done every time.
static private final Method COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);
...
IoUtil.processDirectory(root,new Callback(this,COUNT),selector);
...
private void callback_count(File dir, File fil) {
if(fil!=null) { // file is null for processing a directory
fileTotal++;
if(fil.length()>fileSizeLimit) {
throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);
}
}
progress("Counting",dir,fileTotal);
}
IoUtil.processDirectory():
/**
* Process a directory using callbacks. To interrupt, the callback must throw an (unchecked) exception.
* Subdirectories are processed only if the selector is null or selects the directories, and are done
* after the files in any given directory. When the callback is invoked for a directory, the file
* argument is null;
* <p>
* The callback signature is:
* <pre> void callback(File dir, File ent);</pre>
* <p>
* @return The number of files processed.
*/
static public int processDirectory(File dir, Callback cbk, FileSelector sel) {
return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);
}
static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {
int cnt=0;
if(!dir.isDirectory()) {
if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }
}
else {
cbk.invoke(dir,(Object[])null);
File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));
if(lst!=null) {
for(int xa=0; xa<lst.length; xa++) {
File ent=lst[xa];
if(!ent.isDirectory()) {
cbk.invoke(dir,ent);
lst[xa]=null;
cnt++;
}
}
for(int xa=0; xa<lst.length; xa++) {
File ent=lst[xa];
if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }
}
}
}
return cnt;
}
This example illustrates the beauty of this approach - the application specific logic is abstracted into the callback, and the drudgery of recursively walking a directory tree is tucked nicely away in a completely reusable static utility method. And we don't have to repeatedly pay the price of defining and implementing an interface for every new use. Of course, the argument for an interface is that it is far more explicit about what to implement (it's enforced, not simply documented) - but in practice I have not found it to be a problem to get the callback definition right.
Defining and implementing an interface is not really so bad (unless you're distributing applets, as I am, where avoiding creating extra classes actually matters), but where this really shines is when you have multiple callbacks in a single class. Not only is being forced to push them each into a separate inner class added overhead in the deployed application, but it's downright tedious to program and all that boiler-plate code is really just "noise".
Actually select
does select but not placing the selected values to the respective field . Where wondered the below snippet works perfectly
driver.findElement(By.name("period")).sendKeys("Last 52 Weeks");
The submit()
function is there to make life easier. You can use it on any element inside of form tags to submit that form.
You can also search for the submit button and use click()
.
So the only difference is click()
has to be done on the submit button and submit()
can be done on any form element.
It's up to you.
http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms
Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.
Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/
In H2, what works for me is:
I code, starting the server like:
server = Server.createTcpServer().start();
That starts the server on localhost
port 9092.
Then, in code, establish a DB connection on the following JDBC URL:
jdbc:h2:tcp://localhost:9092/mem:test;DB_CLOSE_DELAY=-1;MODE=MySQL
While debugging, as a client to inspect the DB I use the one provided by H2, which is good enough, to launch it you just need to launch the following java main separately
org.h2.tools.Console
This will start a web server with an app on 8082, launch a browser on localhost:8082
And then you can enter the previous URL to see the DB
Check any syntax problem in the XMl file. I've found this error when working on xsl/xsp with Cocoon and I define a variable using a non-existing node or something like that. Check the whole XML.
Some of these answers seem unnecessarily complex. Make your tbody:
display: block; height: 300px; overflow-y: auto
Then manually set the widths of each column so that the thead and tbody columns are the same width. Setting the table's style="table-layout: fixed" may also be necessary.
Hold shift and right click on SQL Server Mangement studion icon. You can Run as other windows account user.
npm install --save-dev @fortawesome/fontawesome-free
in index.js
import '@fortawesome/fontawesome-free/css/all.min.css';
then use icons like below :
import React, { Component } from "react";
class Like extends Component {
state = {};
render() {
return <i className="fas fa-heart"></i>;
}
}
export default Like;
Hope this will help .
DECLARE @emp_cond nvarchar(Max) =' ',@LOCATION_ID NUMERIC(18,0)
SET@LOCATION_ID=10110000000
IF CAST(@LOCATION_ID AS VARCHAR(18))<>' '
BEGIN
SELECT @emp_cond= @emp_cond + N' AND
CM.STATIC_EMP_INFO.EMP_ID = ' ' '+ CAST(@LOCATION_ID AS VARCHAR(18)) +' ' ' '
END
print @emp_cond
EXEC( @emp_cond)
range()
can only work with integers, but dividing with the /
operator always results in a float value:
>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
Make the value an integer again:
for i in range(int(c / 10)):
or use the //
floor division operator:
for i in range(c // 10):
querySelector
and querySelectorAll
are a relatively new APIs, whereas getElementById
and getElementsByClassName
have been with us for a lot longer. That means that what you use will mostly depend on which browsers you need to support.
As for the :
, it has a special meaning so you have to escape it if you have to use it as a part of a ID/class name.
MySQL use this system variable to control where you can import you files
mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| secure_file_priv | NULL |
+------------------+-------+
So problem is how to change system variables such as secure_file_priv
.
mysqld
sudo mysqld_safe --secure_file_priv=""
now you may see like this:
mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| secure_file_priv | |
+------------------+-------+
MyClass
is a class not a namespace. So this code is wrong:
using MyClass //THIS CODE IS NOT CORRECT
You should check the namespace of the MyClass
(e.g: MyNamespace). Then call it in a proper way:
MyNamespace.MyClass myClass =new MyNamespace.MyClass();
another option ... needs remoting ...
(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version
Answer is adding this 2 lines of code to Global.asax.cs Application_Start method
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
Reference: Handling Circular Object References
<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a>
</span>
</span>
</div>
In Java, you can use the Collection
interface's removeAll
method.
// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
add("apple");
add("orange");
}};
Collection secondList = new ArrayList() {{
add("apple");
add("orange");
add("banana");
add("strawberry");
}};
// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Remove all elements in firstList from secondList
secondList.removeAll(firstList);
// Show the "after" list
System.out.println("Result: " + secondList);
The above code will produce the following output:
First List: [apple, orange]
Second List: [apple, orange, banana, strawberry]
Result: [banana, strawberry]
I know this question is quite old, but I have not seen this solution here before:
If you rewrite the <body>
tag to.
<body oncontextmenu="return false;">
you can prevent the right click without using javascript.
However, you can't prevent keyboard shortcuts with HTML. For this, you must use Javascript.
Comparator does everything that comparable does, plus more.
| | Comparable | Comparator ._______________________________________________________________________________ Is used to allow Collections.sort to work | yes | yes Can compare multiple fields | yes | yes Lives inside the class you’re comparing and serves | | as a “default” way to compare | yes | yes Can live outside the class you’re comparing | no | yes Can have multiple instances with different method names | no | yes Input arguments can be a list of | just Object| Any type Can use enums | no | yes
I found the best approach to use comparators as anonymous classes as follows:
private static void sortAccountsByPriority(List<AccountRecord> accounts) {
Collections.sort(accounts, new Comparator<AccountRecord>() {
@Override
public int compare(AccountRecord a1, AccountRecord a2) {
return a1.getRank().compareTo(a2.getRank());
}
});
}
You can create multiple versions of such methods right inside the class you’re planning to sort. So you can have:
sortAccountsByPriorityAndType
etc...
Now, you can use these sort methods anywhere and get code reuse. This gives me everything a comparable would, plus more ... so I don’t see any reason to use comparable at all.
I've simply used this javascript code (using jquery but it's not strictly necessary) :
$( "#button" ).on( "click", function(event) {
$(this).attr('href', 'mailto:[email protected]?subject=hello');
});
When users click on the link, we replace the href attribute of the clicked element.
Be careful don't prevent the default comportment (event.preventDefault), we must let do it because we have just replaced the href where to go
I think robots can't see it, the address is protected from spams.
its an implementation of anonymouse class object creation to give ease of writing less code and to save time
if you want to specifically find strings which ends with desired characters then this would help you...
select * from tablename where col_name like '%190'
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
Add your fonts to assets folder in app/src/main/assets make a custom textview like this :
class CustomLightTextView : TextView {
constructor(context: Context) : super(context){
attachFont(context)
}
constructor(context: Context, attrs: AttributeSet): super(context, attrs){
attachFont(context)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
attachFont(context)
}
fun attachFont(context: Context) {
this.setTypeface(FontCache.getInstance().getLightFont(context))
}
}
Add FontCache : So that you don't have to create typeface again and again like :
class FontCache private constructor(){
val fontMap = HashMap<String,Typeface>()
companion object {
private var mInstance : FontCache?=null
fun getInstance():FontCache = mInstance?: synchronized(this){
return mInstance?:FontCache().also { mInstance=it }
}
}
fun getLightFont(context: Context):Typeface?{
if(!fontMap.containsKey("light")){
Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf");
fontMap.put("light",Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf"))
}
return fontMap.get("light")
}
}
And you are done !
P.S.From android O, you can directly add fonts.
The system cannot find the file specified usually means the build failed (which it will for your code as you're missing a #
infront of include
, you have a stray >>
at the end of your cout
line and you need std::
infront of cout) but you have the 'run anyway' option checked which means it runs an executable that doesn't exist. Hit F7 to just do a build and make sure it says '0 errors' before you try running it.
Code which builds and runs:
#include <iostream>
int main()
{
std::cout << "Hello World";
system("pause");
return 0;
}
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
Try below solution, This will also take care when a user enters only blank space in the input field at the first index.
document.getElementById('capitalizeInput').addEventListener("keyup", () => {_x000D_
var inputValue = document.getElementById('capitalizeInput')['value']; _x000D_
if (inputValue[0] === ' ') {_x000D_
inputValue = '';_x000D_
} else if (inputValue) {_x000D_
inputValue = inputValue[0].toUpperCase() + inputValue.slice(1);_x000D_
}_x000D_
document.getElementById('capitalizeInput')['value'] = inputValue;_x000D_
});
_x000D_
<input type="text" id="capitalizeInput" autocomplete="off" />
_x000D_
max-device-width is the device rendering width
@media all and (max-device-width: 400px) {
/* styles for devices with a maximum width of 400px and less
Changes only on device orientation */
}
@media all and (max-width: 400px) {
/* styles for target area with a maximum width of 400px and less
Changes on device orientation , browser resize */
}
The max-width is the width of the target display area means the current size of browser.
I've found my optimal blocksize to be 8 MB (equal to disk cache?) I needed to wipe (some say: wash) the empty space on a disk before creating a compressed image of it. I used:
cd /media/DiskToWash/
dd if=/dev/zero of=zero bs=8M; rm zero
I experimented with values from 4K to 100M.
After letting dd to run for a while I killed it (Ctlr+C) and read the output:
36+0 records in
36+0 records out
301989888 bytes (302 MB) copied, 15.8341 s, 19.1 MB/s
As dd displays the input/output rate (19.1MB/s in this case) it's easy to see if the value you've picked is performing better than the previous one or worse.
My scores:
bs= I/O rate
---------------
4K 13.5 MB/s
64K 18.3 MB/s
8M 19.1 MB/s <--- winner!
10M 19.0 MB/s
20M 18.6 MB/s
100M 18.6 MB/s
Note: To check what your disk cache/buffer size is, you can use sudo hdparm -i /dev/sda
Try Visual Studio Code
After trying many solution i find this one is pretty simple. just open the project in Visual code and delete it. the UI may freeze for some seconds but it will definitely works.I test using many large size node_modules folder with it
Thanks
While the above solutions should work in 90% of the cases, but if you are still reading this answer!!! You are probably trying to connect to a different server than intended. It may be due to a configuration file pointing to a different SQL server than the actual server you think you are trying to connecting to.
Happened to me atleast.
like Paul said, use
conda create --prefix=/users/.../yourEnvName python=x.x
if you are located in the folder in which you want to create your virtual environment, just omit the path and use
conda create --prefix=yourEnvName python=x.x
conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with
source activate yourEnvName
phpPgAdmin might work for you, if you're already familiar with phpMyAdmin.
Please note that development of phpPgAdmin has moved to github per this notice but the SourceForge link above is for historical / documentation purposes.
But really there are dozens of tools that can do this.
Below pattern perfectly works in case of leap year and as well as with normal dates. The date format is : YYYY-MM-DD
<input type="text" placeholder="YYYY-MM-DD" pattern="(?:19|20)(?:(?:[13579][26]|[02468][048])-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))|(?:[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:29|30))|(?:(?:0[13578]|1[02])-31)))" class="form-control " name="eventDate" id="" required autofocus autocomplete="nope">
I got this solution from http://html5pattern.com/Dates. Hope it may help someone.
More info... Some times .swp files might be holded by vm that was running in backgroung. You may see permission denied message when try to delete the files.
You could use a generator expression with a default value and then next
it:
next((x for x in seq if predicate(x)), None)
Although for this one-liner you need to be using Python >= 2.6.
This rather popular article further discusses this issue: Cleanest Python find-in-list function?.
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
Hope this Helps:
public String getSystemTimeInBelowFormat() {
String timestamp = new SimpleDateFormat("yyyy-mm-dd 'T' HH:MM:SS.mmm-HH:SS").format(new Date());
return timestamp;
}
List<String> colors = new ArrayList<>(
Arrays.asList("RED", null, "BLUE", null, "GREEN"));
// using removeIf() + Objects.isNull()
colors.removeIf(Objects::isNull);
If u wanna Select items of List from 2nd list:
MainList.Where(p => 2ndlist.Contains(p.columns from MainList )).ToList();
Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.
First, your IntentFilter must contain an event.
static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
Second, when you send a broadcast, use this same action:
Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);
Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.
Fourth, is your service declared in the AndroidManifest.xml?
Easiest way to do this is close the project. Using file explorer head to the location of that project and delete.
Alot of processes, even simply deleting can be annoying to figure out in studio. Most deleting options a good work around is to delete using file explorer. This is a part of the process tht works for deleting modules as well. Which u will prob find is painful as well
Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:
var json = JSON.stringify({whatver: test});
In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:
Tools ? Options ? Text Editor ? All Languages ? CodeLens
This is not available in the Community Edition
I have no touch
and chmod
command in my cmd.exe
and git update-index --chmod=+x foo.sh
doesn't work for me.
I finally resolve it by setting skip-worktree
bit:
git update-index --skip-worktree --chmod=+x foo.sh
According to this thread on MVC4 css bundling and image references, if you define your bundle as:
bundles.Add(new StyleBundle("~/Content/css/jquery-ui/bundle")
.Include("~/Content/css/jquery-ui/*.css"));
Where you define the bundle on the same path as the source files that made up the bundle, the relative image paths will still work. The last part of the bundle path is really the file name
for that specific bundle (i.e., /bundle
can be any name you like).
This will only work if you are bundling together CSS from the same folder (which I think makes sense from a bundling perspective).
Update
As per the comment below by @Hao Kung, alternatively this may now be achieved by applying a CssRewriteUrlTransformation
(Change relative URL references to CSS files when bundled).
NOTE: I have not confirmed comments regarding issues with rewriting to absolute paths within a virtual directory, so this may not work for everyone (?).
bundles.Add(new StyleBundle("~/Content/css/jquery-ui/bundle")
.Include("~/Content/css/jquery-ui/*.css",
new CssRewriteUrlTransform()));
Matt's solution didn't work for me on OS X, but Paul's did.
The short version from Paul's link is:
Created /usr/local/bin/ssh_session
with the following text:
#!/bin/bash
export SSH_SESSION=1
if [ -z "$SSH_ORIGINAL_COMMAND" ] ; then
export SSH_LOGIN=1
exec login -fp "$USER"
else
export SSH_LOGIN=
[ -r /etc/profile ] && source /etc/profile
[ -r ~/.profile ] && source ~/.profile
eval exec "$SSH_ORIGINAL_COMMAND"
fi
Execute:
chmod +x /usr/local/bin/ssh_session
Add the following to /etc/sshd_config
:
ForceCommand /usr/local/bin/ssh_session
Copy problematic folder into some backup directory and remove it from your SVN working directory. Remember to delete all .svn
hidden directories from the copied folder.
Now update your project, clean-up and commit what has left. Now move your folder back to working directory, add it and commit. Most of the time this workaround works, it seems that basically SVN got confused...
Update: quoting comment by @Mark:
Didn't need to move the folder around, just deleting the
.svn
folder and then svn-adding it worked.
Currently, they are the same. but previously
VARCHAR
is reserved by Oracle to support distinction between NULL
and empty string in future, as ANSI standard prescribes.
VARCHAR2
does not distinguish between a NULL
and empty string, and never will.
Emp_name varchar(10)
- if you enter value less than 10 digits then remaining space cannot be deleted. it used total of 10 spaces.
Emp_name varchar2(10)
- if you enter value less than 10 digits then remaining space is automatically deleted
I believe you are using Bootstrap 3. If so, please try this code, here is the bootply
<header>
<div class="navbar navbar-static-top navbar-default">
<div class="navbar-header">
<a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="glyphicon glyphicon-th-list"></span>
</a>
</div>
<div class="container" style="background:yellow;">
<a href="/">
<img src="img/logo.png" class="logo img-responsive">
</a>
<nav class="navbar-collapse collapse pull-right" style="line-height:150px; height:150px;">
<ul class="nav navbar-nav" style="display:inline-block;">
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
</div>
</div>
</header>
Taken from here:
You can use Notepad++ to accomplish this in three ways. Just so you know, Notepad++ is a more advanced version of Notepad, which supports syntax highlighting of different code files "out of the box" - PHP included!
Download & install it, fire it up, and load up your PHP file. You should automatically see it beautifully coloured (if not, because the file extension is something other than .php, go to Language -> PHP or Language -> P -> PHP).
If you need to change any of the colours, you can easily do so - just go to Settings -> Styler Configurator. From that menu, you can change the various highlighting and font options, to suit your needs - although the default usually suffices for most.
Then, go to Plugins -> NppExport. From there, you have three options you can consider:
Export to RTF Export to HTML Copy all formats to clipboard Start with the last one - "Copy all formats to clipboard" - which will copy the entire file with the highlighted syntax to the clipboard. Once you click it, then open Microsoft Word, and just hit paste! You should see the beautifully syntax-highlighted code. If something goes wrong, then you can try one of the other options (export to RTF/HTML), although I've never had a problem with the clipboard method.
I have run into the same problem as w00, but I didn't had the freedom to rewrite the base functionality of the component in which this problem (E_NOTICE) occured. I've been able to fix the issue using an ArrayObject in stead of the basic type array(). This will return an object, which will defaulty be returned by reference.
Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.
I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.
def reachedGoal(a,b):
if(len(a)!=len(b)):
raise ValueError("Wrong lists provided")
for val1 in range(0,len(a)):
temp1=a[val1]
temp2=b[val1]
for val2 in range(0,len(b)):
if(temp1[val2]!=temp2[val2]):
return False
return True
If the user is running El Capitan or higher, it will work in Chrome with
font-family: 'BlinkMacSystemFont';
select substring( field, 1, 5 ) from sometable
First we can define a new operator,
"%ni%" = Negate( "%in%" )
Then, its like x not in remove
x <- 1:10
remove <- c(2,3,5)
x <- x[ x %ni% remove ]
or why to go for remove, go directly
x <- x[ x %ni% c(2,3,5)]
Are you always going to prepend a backslash? If so, try
import re
rx = re.compile('([&#])')
# ^^ fill in the characters here.
strs = rx.sub('\\\\\\1', strs)
It may not be the most efficient method but I think it is the easiest.
The advantages of an abstract class are:
Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.
Knowing how to write a preset dictionary is useful to know as well:
cmap = {'US':'USA','GB':'Great Britain'}
# Explicitly:
# -----------
def cxlate(country):
try:
ret = cmap[country]
except KeyError:
ret = '?'
return ret
present = 'US' # this one is in the dict
missing = 'RU' # this one is not
print cxlate(present) # == USA
print cxlate(missing) # == ?
# or, much more simply as suggested below:
print cmap.get(present,'?') # == USA
print cmap.get(missing,'?') # == ?
# with country codes, you might prefer to return the original on failure:
print cmap.get(present,present) # == USA
print cmap.get(missing,missing) # == RU
-- searching for weather stations with missing half-hourly records
SELECT stationid
FROM weather_data
WHERE `Timestamp` LIKE '2011-11-15 %' AND
stationid IN (SELECT `ID` FROM `weather_stations`)
GROUP BY stationid
HAVING COUNT(*) != 48;
-- variation of yapiskan with a where .. in .. select
Setting time interval to check for fix is not a good choice.. i noticed that onLocationChanged is not called if you are not moving.. what is understandable since location is not changing :)
Better way would be for example:
Try it
<?php
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>
<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);
alert(count.length);
</script>
C99 is available online. Quoted from www.open-std.org:
The lastest publically available version of the standard is the combined C99 + TC1 + TC2 + TC3, WG14 N1256, dated 2007-09-07. This is a WG14 working paper, but it reflects the consolidated standard at the time of issue.
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
You can also group multiple commands in the one liner
[ -f "filename" ] || ( echo test1 && echo test2 && echo test3 )
or
[ -f "filename" ] || { echo test1 && echo test2 && echo test3 ;}
If filename doesn't exit, the output will be
test1
test2
test3
Note: ( ... ) runs in a subshell, { ... ;} runs in the same shell. The curly bracket notation works in bash only.
Suppose you want to give attributes to an instance which was previously not written in code.
The setattr()
does just that.
It takes the instance of the class self
and key and value to set.
class Example:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
Needs ensure library but you can compare list by:
ensure([1, 2]).contains_only([2, 1])
This will not raise assert exception. Documentation of thin is really thin so i would recommend to look at ensure's codes on github
Develop iOS Apps on Windows With Cross-Platform Tools
Cross-platform tools are awesome: you code your app once, and export it to iOS and Android. That could potentially cut your app development time and cost in half. Several cross-platform tools allow you to develop iOS apps on a Windows PC, or allow you to compile the app if there’s a Mac in your local network.
Well, not so fast…
The cross-platform tool ecosystem is very large. On the one side you have complete Integrated Development Environments (IDEs) like Xamarin, that allow you to build cross-platform apps with C#.
The middle ground is covered by tools like PhoneGap, Cordova, Ionic and Appcelerator, that let you build native apps with HTML5 components. The far end includes smaller platforms like React Native that allow you to write native apps with a JavaScript wrapper.
The one thing that stands out for all cross-platform tools is this: they’re not beginner friendly! It’s much easier to get access to a Mac, learn Swift, and build a simple app, than it is to get started with Xamarin.
Most of the cross-platform tools require you to have a basic understanding of programming, compilation options, and the iOS and Android ecosystems. That’s something you don’t really have as a beginner developer!
Having said that, let’s look at a couple of options:
If you’re familiar with Windows-based development tools and IDEs, and if you already know how to code, it’s worthwhile to check out Xamarin. With Xamarin you code apps in C#, for multiple platforms, using the Mono and MonoTouch frameworks. If you’re familiar with web-based development, check out PhoneGap or Ionic. You’ll feel right at home with HTML 5, CSS and JavaScript. Don’t forget: a native app works different than a website… If you’re familiar with JavaScript, or if you’d rather learn to code JavaScript than Swift, check out React Native. With React Native you can code native apps for iOS and Android using a “wrapper”. Always deliberately choose for cross-platform tools because it’s a smart option, not because you think a native platform language is bad. The fact that one option isn’t right, doesn’t immediately make another option smarter!
If you don’t want to join the proprietary closed Apple universe, don’t forget that many cross-platform tools are operated by equally evil companies like Google, Facebook, Microsoft, Adobe and Amazon.
An often heard argument against cross-platform tools is that they offer limited access to and support for smartphone hardware, and are less “snappy” than their native counterparts. Keep in mind that any cross-platform tool will require you to write platform-specific code at one point, especially if you want to code custom features.
I had the same problem of @rutherford, today the new phpMyAdmin's 3.4.11.1 GUI is different, so I figure out it's better if someone improves the answers with updated info.
Full mysql logs can be found in:
"Status"->"Binary Log"
This is the answer, doesn't matter if you're using MAMP, XAMPP, LAMP, etc.
You should use abstract class to initialize a property. You can't inititalize in Inteface .
You can do it with a LINQ like solution instead of a regular expression:
string input = "123- abcd33";
string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());
A quick performance test shows that this is about five times faster than using a regular expression.
If you have xclip an easy way of copying text to the clipboard is as follows:
y
command in vanilla vim):call system("xclip -selection clipboard", @")
:call system()
runs a terminal command. It takes two arguments, the first the command, the second what to pipe to that command. For example :echom system("head -1", "Hello\nWorld")
returns Hello (With some padding). echom returns the output of a command, call doesn't.
xclip -selection clipboard
just copies text into the system clipboard as opposed to the default X clipboard, (Accessed by the middle moue button).
@"
returns the last yanked text. " is the default register, but you could use any register. To see the contents of all registers, type :registers
.
DA is right. In your own fiddle, the iframe is indeed responsive. You can verify that in firebug by checking iframe box-sizing. But some elements inside that iframe is not responsive, so they "stick out" when window size is small. For example, div#products-post-wrapper
's width is 8800px.
It worked for me just by adding serverTimeZone=UTC on application.properties.
spring.datasource.url=jdbc:mysql://localhost/db?serverTimezone=UTC
This is not specific to sqlite but you can just do
SELECT * FROM ... WHERE UPPER(name) = UPPER('someone')
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Try doing it this way, it worked for me:
$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`
Seems like the rule always has the validation on the first input among the pair...
The implicit make rule for compiling a C program is
%.o:%.c
$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
where the $()
syntax expands the variables. As both CPPFLAGS
and CFLAGS
are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if foo.c
is a file in the current directory
make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"
will both call your compiler in exactly the same way, namely
gcc -I/usr/include -c -o foo.o foo.c
The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have bar.cpp
then try
make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"
then the compilations will be
g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp
as the C++ implicit rule also uses the CPPFLAGS
variable.
This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in CPPFLAGS
, if it's for a specific language put it in CFLAGS
, CXXFLAGS
etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass -std=c99
to your C++ compiler!
You might then end up with something like this in your makefile
CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++
If possible, check out SSIS (SQL Server Integration Services). I am just getting my feet wet with this toolkit, but already am looping over 40+ servers and preparing to wreak all kinds of havoc ;)
In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().
When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that
SELECT CASE
WHEN transaction_isolation_level = 1
THEN 'READ UNCOMMITTED'
WHEN transaction_isolation_level = 2
AND is_read_committed_snapshot_on = 1
THEN 'READ COMMITTED SNAPSHOT'
WHEN transaction_isolation_level = 2
AND is_read_committed_snapshot_on = 0 THEN 'READ COMMITTED'
WHEN transaction_isolation_level = 3
THEN 'REPEATABLE READ'
WHEN transaction_isolation_level = 4
THEN 'SERIALIZABLE'
WHEN transaction_isolation_level = 5
THEN 'SNAPSHOT'
ELSE NULL
END AS TRANSACTION_ISOLATION_LEVEL
FROM sys.dm_exec_sessions AS s
CROSS JOIN sys.databases AS d
WHERE session_id = @@SPID
AND d.database_id = DB_ID();
Use:
$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
if(e.keyCode == 13) {
e.preventDefault();
return false;
}
});
This solution works on all forms on a website (also on forms inserted with Ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.
'OR 1=1
is an attempt to make a query succeed no matter what
The /*
is an attempt to start a multiline comment so the rest of the query is ignored.
An example would be
SELECT userid
FROM users
WHERE username = ''OR 1=1/*'
AND password = ''
AND domain = ''
As you can see if you were to populate the username field without escaping the '
no matter what credentials the user passes in the query would return all userids in the system likely granting access to the attacker (possibly admin access if admin is your first user). You will also notice the remainder of the query would be commented out because of the /*
including the real '
.
The fact that you can see the value in your database means that it was escaped and that particular attack did not succeed. However, you should investigate if any other attempts were made.
Start From the material design update, it support app:strokeColor
and also app:strokeWidth
. see more
to use material design update. add following code to build.gradle
(:app)
dependencies {
// ...
implementation 'com.google.android.material:material:1.0.0'
// ...
}
and Change CardView
to MaterialCardView
std::vector
has a method size()
which returns the number of elements in the vector.
(Yes, this is tongue-in-cheek answer)
Edit/Create an .htaccess
file inside /galerias
with this:
Options -Indexes
Directory browsing is provided by the mod_autoindex module.
This is what I did and it works try and play around with it. It calculates total,avarage,minimum and maximum.
public static void main(String[] args) {
int[] score= {56,90,89,99,59,67};
double avg;
int sum=0;
int maxValue=0;
int minValue=100;
for(int i=0;i<6;i++){
sum=sum+score[i];
if(score[i]<minValue){
minValue=score[i];
}
if(score[i]>maxValue){
maxValue=score[i];
}
}
avg=sum/6.0;
System.out.print("Max: "+maxValue+"," +" Min: "+minValue+","+" Avarage: "+avg+","+" Sum: "+sum);}
}
You can Do this
var array = [];
// assigning values to corresponding keys
array[0] = "Main page";
array[1] = "Guide page";
array[2] = "Articles page";
array[3] = "Forum board";
array.forEach(value => {
console.log(value)
})
In addition to Mathias answer.
Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable
:
$ Get-Variable
Name Value
---- -----
$ name
? True
^ gci
args {}
ChocolateyTabSettings @{AllCommands=False}
ConfirmPreference High
DebugPreference SilentlyContinue
EnabledExperimentalFeatures {}
Error {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference Continue
ErrorView NormalView
ExecutionContext System.Management.Automation.EngineIntrinsics
false False
FormatEnumerationLimit 4
...
These also include stuff you may have set in your profile startup script.
&>out time command >/dev/null
in your case
&>out time sleep 1 >/dev/null
then
cat out
For me, I forgot to add the default serial id.
private static final long serialVersionUID = 1L;
use this as somethink
"C:/Program Files (x86)/Nox/bin/nox_adb" install -r app.apk
where
"path_to_executable" commands_argument
It's not possible with Notepad but HERE'S THE EASY SOLUTION:
You will need the freeware Expresso v3.1 http://www.ultrapico.com/ExpressoDownload.htm
I resorted to another piece of free software: Expresso by Ultrapico.
Paste your whole text to be searched into the "Sample text" pane of Expresso,
Press the "Run match" button. Right click in the "Search results pane" and "Export to..." or "Copy matched text to clipboard".
N.B.: The original author is @Andreas Jansson but it is hidden in a comment, so since this page is high ranked in Google Search I leave it here for others.
Please see my class that is a scrollable frame. It's vertical scrollbar is binded to <Mousewheel>
event as well. So, all you have to do is to create a frame, fill it with widgets the way you like, and then make this frame a child of my ScrolledWindow.scrollwindow
. Feel free to ask if something is unclear.
Used a lot from @ Brayan Oakley answers to close to this questions
class ScrolledWindow(tk.Frame):
"""
1. Master widget gets scrollbars and a canvas. Scrollbars are connected
to canvas scrollregion.
2. self.scrollwindow is created and inserted into canvas
Usage Guideline:
Assign any widgets as children of <ScrolledWindow instance>.scrollwindow
to get them inserted into canvas
__init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs)
docstring:
Parent = master of scrolled window
canv_w - width of canvas
canv_h - height of canvas
"""
def __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs):
"""Parent = master of scrolled window
canv_w - width of canvas
canv_h - height of canvas
"""
super().__init__(parent, *args, **kwargs)
self.parent = parent
# creating a scrollbars
self.xscrlbr = ttk.Scrollbar(self.parent, orient = 'horizontal')
self.xscrlbr.grid(column = 0, row = 1, sticky = 'ew', columnspan = 2)
self.yscrlbr = ttk.Scrollbar(self.parent)
self.yscrlbr.grid(column = 1, row = 0, sticky = 'ns')
# creating a canvas
self.canv = tk.Canvas(self.parent)
self.canv.config(relief = 'flat',
width = 10,
heigh = 10, bd = 2)
# placing a canvas into frame
self.canv.grid(column = 0, row = 0, sticky = 'nsew')
# accociating scrollbar comands to canvas scroling
self.xscrlbr.config(command = self.canv.xview)
self.yscrlbr.config(command = self.canv.yview)
# creating a frame to inserto to canvas
self.scrollwindow = ttk.Frame(self.parent)
self.canv.create_window(0, 0, window = self.scrollwindow, anchor = 'nw')
self.canv.config(xscrollcommand = self.xscrlbr.set,
yscrollcommand = self.yscrlbr.set,
scrollregion = (0, 0, 100, 100))
self.yscrlbr.lift(self.scrollwindow)
self.xscrlbr.lift(self.scrollwindow)
self.scrollwindow.bind('<Configure>', self._configure_window)
self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel)
self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel)
return
def _bound_to_mousewheel(self, event):
self.canv.bind_all("<MouseWheel>", self._on_mousewheel)
def _unbound_to_mousewheel(self, event):
self.canv.unbind_all("<MouseWheel>")
def _on_mousewheel(self, event):
self.canv.yview_scroll(int(-1*(event.delta/120)), "units")
def _configure_window(self, event):
# update the scrollbars to match the size of the inner frame
size = (self.scrollwindow.winfo_reqwidth(), self.scrollwindow.winfo_reqheight())
self.canv.config(scrollregion='0 0 %s %s' % size)
if self.scrollwindow.winfo_reqwidth() != self.canv.winfo_width():
# update the canvas's width to fit the inner frame
self.canv.config(width = self.scrollwindow.winfo_reqwidth())
if self.scrollwindow.winfo_reqheight() != self.canv.winfo_height():
# update the canvas's width to fit the inner frame
self.canv.config(height = self.scrollwindow.winfo_reqheight())
Here are quite a few ways to add dictionaries.
You can use Python3's dictionary unpacking feature.
ndic = {**dic0, **dic1}
Or create a new dict by adding both items.
ndic = dict(dic0.items() + dic1.items())
If your ok to modify dic0
dic0.update(dic1)
If your NOT ok to modify dic0
ndic = dic0.copy()
ndic.update(dic1)
If all the keys in one dict are ensured to be strings (dic1
in this case, of course args can be swapped)
ndic = dict(dic0, **dic1)
In some cases it may be handy to use dict comprehensions (Python 2.7 or newer),
Especially if you want to filter out or transform some keys/values at the same time.
ndic = {k: v for d in (dic0, dic1) for k, v in d.items()}
You can also take a look at x-ray: https://github.com/lapwinglabs/x-ray
Alternative
If your console is not empty, right click on the Console area > Preferences... > change the value for the Console buffer size (characters) (recommended) or uncheck the Limit console output (not recommended):
According to caniuse.com:
You can use a client-only polyfill to extend support of SSE to many other browsers. This is less likely with WebSockets. Some EventSource polyfills:
If you need to support all the browsers, consider using a library like web-socket-js, SignalR or socket.io which support multiple transports such as WebSockets, SSE, Forever Frame and AJAX long polling. These often require modifications to the server side as well.
Learn more about SSE from:
Learn more about WebSockets from:
Other differences:
I understand that
std::atomic<>
makes an object atomic.
That's a matter of perspective... you can't apply it to arbitrary objects and have their operations become atomic, but the provided specialisations for (most) integral types and pointers can be used.
a = a + 12;
std::atomic<>
does not (use template expressions to) simplify this to a single atomic operation, instead the operator T() const volatile noexcept
member does an atomic load()
of a
, then twelve is added, and operator=(T t) noexcept
does a store(t)
.
Just open your repository file and add this new function, then call it inside your controller:
public function distinctCategories(){
return $this->createQueryBuilder('cc')
->where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->groupBy('cc.blogarticle')
->getQuery()
->getResult()
;
}
Then within your controller:
public function index(YourRepository $repo)
{
$distinctCategories = $repo->distinctCategories();
return $this->render('your_twig_file.html.twig', [
'distinctCategories' => $distinctCategories
]);
}
Good luck!
File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As @Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
The following syntax fixes it for you:
curl -v -F key1=value1 -F upload=@localfilename URL
Amit-
I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:
CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;
Drop the table you want to add columns to:
DROP TABLE TABLE_TO_CHANGE;
It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".
Now insert the data back into the new table:
INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;
When the data is inserted into your "new-old" table, you can drop the temp table.
DROP TABLE MY_TEMP_TABLE;
This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.
-CJ
In your invocation, the two functions are the same.
average
can compute a weighted average though.
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
HTML5 introduced a file upload api that allows you to monitor the progress of file uploads but for older browsers there's plupload a framework that specifically made to monitor file uploads and give information about them. plus it has plenty of callbacks so it can work across all browsers
vbc=$(git rev-parse --abbrev-ref HEAD)
vbc_col=$(( $(git show-branch | grep '^[^\[]*\*' | head -1 | cut -d* -f1 | wc -c) - 1 ))
swimming_lane_start_row=$(( $(git show-branch | grep -n "^[\-]*$" | cut -d: -f1) + 1 ))
git show-branch | tail -n +$swimming_lane_start_row | grep -v "^[^\[]*\[$vbc" | grep "^.\{$vbc_col\}[^ ]" | head -n1 | sed 's/.*\[\(.*\)\].*/\1/' | sed 's/[\^~].*//'
Achieves the same ends as Mark Reed's answer, but uses a much safer approach that doesn't misbehave in a number of scenarios:
-
not *
*
The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html
The method DocumentBuilder.parse(String)
takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream
or Reader
, for example a StringReader
. ... Welcome to the Java standard levels of indirections !
Basically :
DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
Note that if you read your XML from a file, you can directly give the File
object to DocumentBuilder.parse()
.
As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !
The following method doesn't require root and should work anywhere (according to docs, even on Android Q+, if you keep targetSdkVersion = 28
).
Make a blank app.
Create a ContentProvider
:
class ApiProvider : ContentProvider() {
private val wifiManager: WifiManager? by lazy(LazyThreadSafetyMode.NONE) {
requireContext().getSystemService(WIFI_SERVICE) as WifiManager?
}
private fun requireContext() = checkNotNull(context)
private val matcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI("wifi", "enable", 0)
addURI("wifi", "disable", 1)
}
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
when (matcher.match(uri)) {
0 -> {
enforceAdb()
withClearCallingIdentity {
wifiManager?.isWifiEnabled = true
}
}
1 -> {
enforceAdb()
withClearCallingIdentity {
wifiManager?.isWifiEnabled = false
}
}
}
return null
}
private fun enforceAdb() {
val callingUid = Binder.getCallingUid()
if (callingUid != 2000 && callingUid != 0) {
throw SecurityException("Only shell or root allowed.")
}
}
private inline fun <T> withClearCallingIdentity(block: () -> T): T {
val token = Binder.clearCallingIdentity()
try {
return block()
} finally {
Binder.restoreCallingIdentity(token)
}
}
override fun onCreate(): Boolean = true
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
override fun getType(uri: Uri): String? = null
}
Declare it in AndroidManifest.xml
along with necessary permission:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application>
<provider
android:name=".ApiProvider"
android:authorities="wifi"
android:exported="true" />
</application>
Build the app and install it.
Call from ADB:
adb shell content query --uri content://wifi/enable
adb shell content query --uri content://wifi/disable
Make a batch script/shell function/shell alias with a short name that calls these commands.
Depending on your device you may need additional permissions.
HTML5 has provided new attribute multiple for input element whose type attribute is file. So you can select multiple files and IE9 and previous versions does not support this.
NOTE: be carefull with the name of the input element. when you want to upload multiple file you should use array and not string as the value of the name attribute.
ex:
input type="file" name="myPhotos[]" multiple="multiple"
and if you are using php then you will get the data in $_FILES and use var_dump($_FILES) and see output and do processing Now you can iterate over and do the rest
package com.dataload;
public class insertCSV
{
public static void main(String args[])
{
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationcontext.xml");
// retrieve configured instance
JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
Job job = context.getBean("job", Job.class);
JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
}
}
You can use Reflections framework for this
import static org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation));
If the extra entries in the log bother you but an extra second of start-up time doesn't, just add this to your logging.properties
and forget about it:
org.apache.jasper.servlet.TldScanner.level = WARNING
I tried all above solution and fail, it just added a null file to the DB.
However, I was able to get it done by moving the image(fileName.jpg
) file first in to below folder(in my case) C:\ProgramData\MySQL\MySQL Server 5.7\Uploads
and then I executed below command and it works for me,
INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/fileName.jpg'));
Hope this helps.
As an addition to other answers, unix considers everything as a file system. Your keyboard is a file that is read only from the perspective of the kernel. The screen is a write only file. Similarly, folders, input-output devices etc are also considered to be files. Whenever a file is opened, say when the device drivers[for device files] requests an open(), or a process opens an user file the kernel allocates a file descriptor, an integer that specifies the access to that file such it being read only, write only etc. [for reference : https://en.wikipedia.org/wiki/Everything_is_a_file ]
Usually the better way is to trigger an event (click) instead of calling the method directly.
Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.
Well, "no way" does not mean its impossible:
I tried all the recommendations listed here. What worked for me was to go to server.properties
and add:
port = 9092
advertised.host.name = localhost
Leave listeners
and advertised_listeners
commented out.
Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower depending on the library/use case)
A really simple approach:
class CustomError(Exception):
pass
raise CustomError("Hmm, seems like this was custom coded...")
Or, have the error raise without printing __main__
(may look cleaner and neater):
class CustomError(Exception):
__module__ = Exception.__module__
raise CustomError("Improved CustomError!")
I had a similar issue using Apache 2.4 and PHP 7.
My client sent a lot of requests when refreshing (hard reloading) my application page in the browser and every time some of the last requests resulted in this error in console:
GET
http://example.com/api/v1/my/resource
net::ERR_CONNECTION_RESET
It turned out that my client was reaching the maximum amount of threads that was allowed. The threads exceeding this configured ceiling are simply not handled by Apache at all resulting in the connection reset error response.
The amount of threads can be easily raised by setting the ThreadsPerChild
value for the module in question.
The easiest way to make such change is to uncomment the Server-pool management config file conf/extra/httpd-mpm.conf
and then editing the preset values in the file to desired values.
1) Uncomment the Server-pool management file
# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf
2) Open and edit the file conf/extra/httpd-mpm.conf
and raise the amount of threads
In my case I had to change the threads for the mpm_winnt_module
:
# raised the amount of threads for mpm_winnt_module to 250
<IfModule mpm_winnt_module>
ThreadsPerChild 250
MaxConnectionsPerChild 0
</IfModule>
A comprehensive explanation on these Server-pool management configuration settings can be found in this post on StackOverflow.
Socket are characterized by their domain, type and transport protocol. Common domains are:
AF_UNIX: address format is UNIX pathname
AF_INET: address format is host and port number
(there are actually many other options which can be used here for specialized purposes).usually we use AF_INET for socket programming
Reference: http://www.cs.uic.edu/~troy/fall99/eecs471/sockets.html
Here is a single-liner of how you can delete ALL browser network cache using Cache.delete()
caches.keys().then((keyList) => Promise.all(keyList.map((key) => caches.delete(key))))
Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
Maybe this will help
http://www.math.utah.edu/docs/info/gawk_5.html
awk '$3 ~ /snow|snowman/' dummy_file
Remove the outline when focus is on element, using below CSS property:
input:focus {
outline: 0;
}
This CSS property removes the outline for all input fields on focus or use pseudo class to remove outline of element using below CSS property.
.className input:focus {
outline: 0;
}
This property removes the outline for selected element.
getYears(date1, date2) {
let years = new Date(date1).getFullYear() - new Date(date2).getFullYear();
let month = new Date(date1).getMonth() - new Date(date2).getMonth();
let dateDiff = new Date(date1).getDay() - new Date(date2).getDay();
if (dateDiff < 0) {
month -= 1;
}
if (month < 0) {
years -= 1;
}
return years;
}
This solution caters for http, https and the other normal url type special characters :
import re
def remove_urls (vTEXT):
vTEXT = re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b', '', vTEXT, flags=re.MULTILINE)
return(vTEXT)
print( remove_urls("this is a test https://sdfs.sdfsdf.com/sdfsdf/sdfsdf/sd/sdfsdfs?bob=%20tree&jef=man lets see this too https://sdfsdf.fdf.com/sdf/f end"))
Do this way:-
String newline = System.getProperty("line.separator");
private static final String mText = "SHOP MA" + newline +
+ "----------------------------" + newline +
+ "Pannampitiya" + newline +
+ "09-10-2012 harsha no: 001" + newline +
+ "No Item Qty Price Amount" + newline +
+ "1 Bread 1 50.00 50.00" + newline +
+ "____________________________" + newline;
Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?
x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)
1) If the Map can be immutable:
Collections.emptyMap()
// or, in some cases:
Collections.<String, String>emptyMap()
You'll have to use the latter sometimes when the compiler cannot automatically figure out what kind of Map is needed (this is called type inference). For example, consider a method declared like this:
public void foobar(Map<String, String> map){ ... }
When passing the empty Map directly to it, you have to be explicit about the type:
foobar(Collections.emptyMap()); // doesn't compile
foobar(Collections.<String, String>emptyMap()); // works fine
2) If you need to be able to modify the Map, then for example:
new HashMap<String, String>()
(as tehblanx pointed out)
Addendum: If your project uses Guava, you have the following alternatives:
1) Immutable map:
ImmutableMap.of()
// or:
ImmutableMap.<String, String>of()
Granted, no big benefits here compared to Collections.emptyMap()
. From the Javadoc:
This map behaves and performs comparably to
Collections.emptyMap()
, and is preferable mainly for consistency and maintainability of your code.
2) Map that you can modify:
Maps.newHashMap()
// or:
Maps.<String, String>newHashMap()
Maps
contains similar factory methods for instantiating other types of maps as well, such as TreeMap
or LinkedHashMap
.
Update (2018): On Java 9 or newer, the shortest code for creating an immutable empty map is:
Map.of()
...using the new convenience factory methods from JEP 269.
MySQL documentation covers this topic.
Here is a synopsis. When using join
or inner join
, the on
condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join
. Similarly, you can use an on
clause with cross join
, which also differs from standard SQL.
A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.
In practice, if you want to do a cross join, then use cross join
:
from A cross join B
is much better than:
from A, B
and:
from A join B -- with no on clause
The on
clause is required for a right or left outer join, so the discussion is not relevant for them.
If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.
You can import json files by using the node.js v14 experimental json modules flag. More details here
file.js
import data from './folder/file.json'
export default {
foo () {
console.log(data)
}
}
And you call it with node --experimental-json-modules file.js
I've tried this and it worked for me,
curl -O https://files.pythonhosted.org/packages/c0/4d/d2cd1171f93245131686b67d905f38cab53bf0edc3fd1a06b9c667c9d046/boto3-1.14.29.tar.gz
tar -zxvf boto3-1.14.29.tar.gz
cd boto3-1.14.29/
Replace X with your required python interpreter, for mine it was python3
sudo pythonX setup.py install
Here is my solution by grabbing help from various sources. It takes full web page screen capture and it crops it (optional) and generates thumbnail from the cropped image also. Following are the requirements:
Requirements:
npm -g install phantomjs
import os
from subprocess import Popen, PIPE
from selenium import webdriver
abspath = lambda *p: os.path.abspath(os.path.join(*p))
ROOT = abspath(os.path.dirname(__file__))
def execute_command(command):
result = Popen(command, shell=True, stdout=PIPE).stdout.read()
if len(result) > 0 and not result.isspace():
raise Exception(result)
def do_screen_capturing(url, screen_path, width, height):
print "Capturing screen.."
driver = webdriver.PhantomJS()
# it save service log file in same directory
# if you want to have log file stored else where
# initialize the webdriver.PhantomJS() as
# driver = webdriver.PhantomJS(service_log_path='/var/log/phantomjs/ghostdriver.log')
driver.set_script_timeout(30)
if width and height:
driver.set_window_size(width, height)
driver.get(url)
driver.save_screenshot(screen_path)
def do_crop(params):
print "Croping captured image.."
command = [
'convert',
params['screen_path'],
'-crop', '%sx%s+0+0' % (params['width'], params['height']),
params['crop_path']
]
execute_command(' '.join(command))
def do_thumbnail(params):
print "Generating thumbnail from croped captured image.."
command = [
'convert',
params['crop_path'],
'-filter', 'Lanczos',
'-thumbnail', '%sx%s' % (params['width'], params['height']),
params['thumbnail_path']
]
execute_command(' '.join(command))
def get_screen_shot(**kwargs):
url = kwargs['url']
width = int(kwargs.get('width', 1024)) # screen width to capture
height = int(kwargs.get('height', 768)) # screen height to capture
filename = kwargs.get('filename', 'screen.png') # file name e.g. screen.png
path = kwargs.get('path', ROOT) # directory path to store screen
crop = kwargs.get('crop', False) # crop the captured screen
crop_width = int(kwargs.get('crop_width', width)) # the width of crop screen
crop_height = int(kwargs.get('crop_height', height)) # the height of crop screen
crop_replace = kwargs.get('crop_replace', False) # does crop image replace original screen capture?
thumbnail = kwargs.get('thumbnail', False) # generate thumbnail from screen, requires crop=True
thumbnail_width = int(kwargs.get('thumbnail_width', width)) # the width of thumbnail
thumbnail_height = int(kwargs.get('thumbnail_height', height)) # the height of thumbnail
thumbnail_replace = kwargs.get('thumbnail_replace', False) # does thumbnail image replace crop image?
screen_path = abspath(path, filename)
crop_path = thumbnail_path = screen_path
if thumbnail and not crop:
raise Exception, 'Thumnail generation requires crop image, set crop=True'
do_screen_capturing(url, screen_path, width, height)
if crop:
if not crop_replace:
crop_path = abspath(path, 'crop_'+filename)
params = {
'width': crop_width, 'height': crop_height,
'crop_path': crop_path, 'screen_path': screen_path}
do_crop(params)
if thumbnail:
if not thumbnail_replace:
thumbnail_path = abspath(path, 'thumbnail_'+filename)
params = {
'width': thumbnail_width, 'height': thumbnail_height,
'thumbnail_path': thumbnail_path, 'crop_path': crop_path}
do_thumbnail(params)
return screen_path, crop_path, thumbnail_path
if __name__ == '__main__':
'''
Requirements:
Install NodeJS
Using Node's package manager install phantomjs: npm -g install phantomjs
install selenium (in your virtualenv, if you are using that)
install imageMagick
add phantomjs to system path (on windows)
'''
url = 'http://stackoverflow.com/questions/1197172/how-can-i-take-a-screenshot-image-of-a-website-using-python'
screen_path, crop_path, thumbnail_path = get_screen_shot(
url=url, filename='sof.png',
crop=True, crop_replace=False,
thumbnail=True, thumbnail_replace=False,
thumbnail_width=200, thumbnail_height=150,
)
These are the generated images:
Set npm registry globally
use the below command to modify the .npmrc config file for the logged in user
npm config set registry <registry url>
Example: npm config set registry https://registry.npmjs.org/
Set npm registry Scope
Scopes allow grouping of related packages together. Scoped packages will be installed in a sub-folder under node_modules folder.
Example: node_modules/@my-org/packagaename
To set the scope registry use: npm config set @my-org:registry http://example.reg-org.com
To install packages using scope use: npm install @my-org/mypackage
whenever you install any packages from scope @my-org npm will search in the registry setting linked to scope @my-org for the registry url.
Set npm registry locally for a project
To modify the npm registry only for the current project. create a file inside the root folder of the project as .npmrc
Add the below contents in the file
registry = 'https://registry.npmjs.org/'
Try git diff origin/master..master
(assuming that origin/master
is your upstream). Unlike git push --dry-run
, this still works even if you don't have write permission to the upstream.
Just add public properties to the user control.
You can add [Category("MyCategory")]
and [Description("A property that controls the wossname")]
attributes to make it nicer, but as long as it's a public property it should show up in the property panel.
I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:
String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";
The first is evaluated at compile-time. The second is evaluated at run-time.
So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.
If the characters are constant, this is fine:
String s = "" + 'a' + 'b' + 'c';
If however they aren't, consider this:
String concat(char... chars) {
if (chars.length == 0) {
return "";
}
StringBuilder s = new StringBuilder(chars.length);
for (char c : chars) {
s.append(c);
}
return s.toString();
}
as an appropriate solution.
However some might be tempted to optimise:
String s = "Name: '" + name + "'"; // String name;
into this:
String s = new StringBuilder().append("Name: ").append(name).append("'").toString();
While this is well-intentioned, the bottom line is DON'T.
Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.
For low-level optimisation the compiler is better at optimising code than you are.
Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.
I guess your code relates to Windows Forms.
You call BeginInvoke
if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)
If BeginInvoke
is called for Delegate
type the delegate is just invoked asynchronously.
(Invoke
for the sync version.)
If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task
with the according context. (TaskScheduler.FromCurrentSynchronizationContext()
)
And to add a little to already said by others:
Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var
with lambdas: compiler needs a hint.
UPDATE:
this requires .Net v4.0 and higher
// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);
// also can be called anywhere. Task will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked)
task.Start(scheduler);
If you started the task from other thread and need to wait for its completition task.Wait()
will block calling thread till the end of the task.
Read more about tasks here.
Janky at best
<a href="file://///server/folders/x/x/filename.ext">right click </a></td>
and then right click, select "copy location" option, and then paste into url.
You will get 6 7 printed as, as is easily tested, and here's the reason: When foo
is first called, the static variable x is initialized to 5. Then it is incremented to 6 and printed.
Now for the next call to foo
. The program skips the static variable initialization, and instead uses the value 6 which was assigned to x the last time around. The execution proceeds as normal, giving you the value 7.
I had the same trouble with Vagrant 1.6.5 and Virtual Box 4.3.16. The solution described at https://github.com/mitchellh/vagrant/issues/4470 worked fine for me, I just had to remove VirtualBox 4.3.16 and install the older version 4.3.12.
Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.
After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer
and custom XML serialization via IXmlSerialiazble
.
To whit, I'll use the same MyTypeWithNamespaces
XML sample that's been used in the answers to this question so far.
[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
// Don't do this!! Microsoft's documentation explicitly says it's not supported.
// It doesn't throw any exceptions, but in my testing, it didn't always work.
// new XmlQualifiedName(string.Empty, string.Empty), // And don't do this:
// new XmlQualifiedName("", "")
// DO THIS:
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
// Add any other namespaces, with prefixes, here.
});
}
// If you have other constructors, make sure to call the default constructor.
public MyTypeWithNamespaces(string label, int epoch) : this( )
{
this._label = label;
this._epoch = epoch;
}
// An element with a declared namespace different than the namespace
// of the enclosing type.
[XmlElement(Namespace="urn:Whoohoo")]
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _label;
// An element whose tag will be the same name as the property name.
// Also, this element will inherit the namespace of the enclosing type.
public int Epoch
{
get { return this._epoch; }
set { this._epoch = value; }
}
private int _epoch;
// Per Microsoft's documentation, you can add some public member that
// returns a XmlSerializerNamespaces object. They use a public field,
// but that's sloppy. So I'll use a private backed-field with a public
// getter property. Also, per the documentation, for this to work with
// the XmlSerializer, decorate it with the XmlNamespaceDeclarations
// attribute.
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
}
That's all to this class. Now, some objected to having an XmlSerializerNamespaces
object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.
Now, when it comes time to serialize the class, you would use the following code:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
/******
OK, I just figured I could do this to make the code shorter, so I commented out the
below and replaced it with what follows:
// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");
******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();
// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.
// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
Once you have done this, you should get the following output:
<MyTypeWithNamespaces>
<Label xmlns="urn:Whoohoo">myLabel</Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces
member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable
.
It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi
and xsd
namespaces generated by the XmlSerializer
.
UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo
. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra
and Whoohoo
. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra
is the default namespace. I could inside my MyTypeWithNamespaces
class add a namespace prefix for the Whoohoo
namespace like so:
public MyTypeWithNamespaces
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
new XmlQualifiedName("w", "urn:Whoohoo")
});
}
Now, in my class definition, I indicated that the <Label/>
element is in the namespace "urn:Whoohoo"
, so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:
<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
<w:Label>myLabel</w:Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Because <Label>
is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi
and xsd
namespaces.
This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label>
is part of the same namespace as the rest of the document, in this case urn:Abracadabra
:
<MyTypeWithNamespaces>
<Label>myLabel<Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
});
}
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
Then, later, in your code that uses the MyTypeWithNamespaces
object to serialize it, you would call it as I did above:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
...
// Above, you'd setup your XmlTextWriter.
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
And the XmlSerializer
would spit back out the same XML as shown immediately above with no additional namespaces in the output:
<MyTypeWithNamespaces>
<Label>myLabel<Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
An alternative solution for invalidating JWTs, without any additional secure storage on the backend, is to implement a new jwt_version
integer column on the users table. If the user wishes to log out or expire existing tokens, they simply increment the jwt_version
field.
When generating a new JWT, encode the jwt_version
into the JWT payload, optionally incrementing the value beforehand if the new JWT should replace all others.
When validating the JWT, the jwt_version
field is compared alongside the user_id
and authorisation is granted only if it matches.
You can use print_r
, var_dump
and var_export
funcations of php:
print_r
: Convert into human readble form
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
var_dump()
: will show you the type of the thing as well as what's in it.
var_dump($results);
foreach loop
: using for each loop you can iterate each and every value of an array.
foreach($results['data'] as $result) {
echo $result['type'].'<br>';
}
Install the debug build of the service and attach the debugger to the service to see what's happening.
This is what I have done. (Adapt from all of your answers)
<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />
It works. Thanks to all of you. :)
You mention already having a background image on body
.
You could set that background image on html
, and the new one on body
. This will of course depend upon your layout, but you wouldn't need to use your footer for it.
$output = file("http://www.example.com");
didn't work until I enabled: allow_url_fopen, allow_url_include,
and file_uploads
in php.ini
for PHP7
mod_log_forensic is what you want, but it may not be included/available with your Apache install by default.
Here is how to use it.
LoadModule log_forensic_module /usr/lib64/httpd/modules/mod_log_forensic.so
<IfModule log_forensic_module>
ForensicLog /var/log/httpd/forensic_log
</IfModule>
You could also simply link both cells, and have an =Cell formula in each column like, =Sheet2!A2
in Sheet 1 A2 and =Sheet2!B2
in Sheet 1 B2, and drag it down, and then sort those two columns the way you want.
This would be better if your unique items change also, then all you would do is sort and be done.
You can use
$window.scrollTo(x, y);
where x
is the pixel along the horizontal axis and y
is the pixel along the vertical axis.
Scroll to top
$window.scrollTo(0, 0);
Focus on element
$window.scrollTo(0, angular.element('put here your element').offsetTop);
Update:
Also you can use $anchorScroll
$(window).on("touchstart", function(ev) {
var e = ev.originalEvent;
console.log(e.touches);
});
I know it been asked a long time ago, but I thought a concrete example might help.
This code will split it up for you:
list($whole, $decimal) = explode('.', $your_number);
where $whole is the whole number and $decimal will have the digits after the decimal point.
You're resetting the margin on all elements in the second css block. Default margin is 40px - this should solve the problem:
.my_container ul {list-style:disc outside none; margin-left:40px;}
Short answer: you can't. Use MSIEXEC /x
Long answer: When you run the MSI file directly at the command line, all that's happening is that it runs MSIEXEC for you. This association is stored in the registry. You can see a list of associations by (in Windows Explorer) going to Tools / Folder Options / File Types.
For example, you can run a .DOC file from the command line, and WordPad or WinWord will open it for you.
If you look in the registry under HKEY_CLASSES_ROOT\.msi
, you'll see that .MSI files are associated with the ProgID "Msi.Package". If you look in HKEY_CLASSES_ROOT\Msi.Package\shell\Open\command
, you'll see the command line that Windows actually uses when you "run" a .MSI file.
You are looking for dynamic_cast<B*>(pointer)
The solution I find is to use custom action Layout: Here is XML for menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:Eventapp="http://schemas.android.com/apk/res-auto">
<!-- This is a comment. -->
<item
android:id="@+id/action_create"
android:actionLayout="@layout/action_view_details_layout"
android:orderInCategory="50"
android:showAsAction = "always"/>
</menu>
The Layout is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:gravity="center"
android:text="@string/create"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:gravity="center"
android:src="@drawable/ic_action_v"/>
</LinearLayout>
this will show the icon and the text together.
To get the clickitem the the fragment or activity:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
//super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_details_fragment, menu);
View view = menu.findItem(R.id.action_create).getActionView();
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
Very often you have no option to setup the sending server so what I did I changed the XMLHttpRequest.open call in my javascript to a local get-file.php file where I have the following code in it:
<?php_x000D_
$file = file($_GET['url']);_x000D_
echo implode('', $file);_x000D_
?>
_x000D_
javascript is doing this:
var xhttp = new XMLHttpRequest();_x000D_
xhttp.onreadystatechange = function() {_x000D_
if (this.readyState == 4 && this.status == 200) {_x000D_
// File content is now in the this.responseText_x000D_
}_x000D_
};_x000D_
xhttp.open("GET", "get-file.php?url=http://site/file", true);_x000D_
xhttp.send();
_x000D_
In my case this solved the restriction/situation just perfectly. No need to hack Firefox or servers. Just load your javascript/html file with that small php file into the server and you're done.
If anyone stumbles across this as it is the first result in google,
remember to specify the filename too in the SaveAs method.
Won't work
file_upload.PostedFile.SaveAs(Server.MapPath(SaveLocation));
You need this:
filename = Path.GetFileName(file_upload.PostedFile.FileName);
file_upload.PostedFile.SaveAs(Server.MapPath(SaveLocation + "\\" + filename));
I assumed the SaveAs method will automatically use the filename uploaded. Kept getting "Access denied" error. Not very descriptive of the actual problem
import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions)
with open('data.csv', 'r') as f:
for rec in csv.DictReader(f):
for l, col in zip(data, cols):
l.append(float(rec[col]))
print data
# [[3.0, 3.0], [0.01, 0.01]]
For alphabetical order following nationalization, use Collator
.
//Get the Collator for US English and set its strength to PRIMARY
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
if( usCollator.compare("abc", "ABC") == 0 ) {
System.out.println("Strings are equivalent");
}
For a list of supported locales, see JDK 8 and JRE 8 Supported Locales.
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too. .....
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
@Brian I use lambdas all the time in C#, in LINQ and non-LINQ operators. Example:
string[] GetCustomerNames(IEnumerable<Customer> customers)
{ return customers.Select(c=>c.Name);
}
Before C#, I used anonymous functions in JavaScript for callbacks to AJAX functions, before the term Ajax was even coined:
getXmlFromServer(function(result) {/*success*/}, function(error){/*fail*/});
The interesting thing with C#'s lambda syntax, though, is that on their own their type cannot be infered (i.e., you can't type var foo = (x,y) => x * y) but depending on which type they're assigned to, they'll be compiled as delegates or abstract syntax trees representing the expression (which is how LINQ object mappers do their "language-integrated" magic).
Lambdas in LISP can also be passed to a quotation operator and then traversed as a list of lists. Some powerful macros are made this way.
"Last day of month
" is actually "First day of *next* month, minus 1
". So here's what I use, no need for "DaysInMonth" method:
public static DateTime FirstDayOfMonth(this DateTime value)
{
return new DateTime(value.Year, value.Month, 1);
}
public static DateTime LastDayOfMonth(this DateTime value)
{
return value.FirstDayOfMonth()
.AddMonths(1)
.AddMinutes(-1);
}
NOTE:
The reason I use AddMinutes(-1)
, not AddDays(-1)
here is because usually you need these date functions for reporting for some date-period, and when you build a report for a period, the "end date" should actually be something like Oct 31 2015 23:59:59
so your report works correctly - including all the data from last day of month.
I.e. you actually get the "last moment of the month" here. Not Last day.
OK, I'm going to shut up now.
You can use the below code to achieve loading jQuery in your JS file. I have also added a jQuery JSFiddle that is working and it's using a self-invoking function.
// Anonymous "self-invoking" function_x000D_
(function() {_x000D_
var startingTime = new Date().getTime();_x000D_
// Load the script_x000D_
var script = document.createElement("SCRIPT");_x000D_
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';_x000D_
script.type = 'text/javascript';_x000D_
document.getElementsByTagName("head")[0].appendChild(script);_x000D_
_x000D_
// Poll for jQuery to come into existance_x000D_
var checkReady = function(callback) {_x000D_
if (window.jQuery) {_x000D_
callback(jQuery);_x000D_
}_x000D_
else {_x000D_
window.setTimeout(function() { checkReady(callback); }, 20);_x000D_
}_x000D_
};_x000D_
_x000D_
// Start polling..._x000D_
checkReady(function($) {_x000D_
$(function() {_x000D_
var endingTime = new Date().getTime();_x000D_
var tookTime = endingTime - startingTime;_x000D_
window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");_x000D_
});_x000D_
});_x000D_
})();
_x000D_
Other Option : - You can also try Require.JS which is a JS module loader.
Both algorithms (AES and twofish) are considered very secure. This has been widely covered in other answers.
However, since AES is much widely used now in 2016, it has been specifically hardware-accelerated in several platforms such as ARM and x86. While not significantly faster than twofish before hardware acceleration, AES is now much faster thanks to the dedicated CPU instructions.
To enable openssl go into php.ini and enable this line:
extension=php_openssl.dll
if you don't want enable openssl you can set to composer not use openssl with this command:
composer config -g -- disable-tls true
however, this is a security problem.
You can use mysql_errno()
for this too.
$result = mysql_query($query);
if(mysql_errno()){
echo "MySQL error ".mysql_errno().": "
.mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}
for xampp vm on MacOS capitan, high sierra, MacOS Mojave (10.12+), you can follow these
1. mount /opt/lampp
2. explore the folder
3. open terminal from the folder
4. cd to `htdocs`>yourapp (ex: techaz.co)
5. vim .htaccess
6. paste your .htaccess content (that is suggested on options-permalink.php)
$ echo "bar embarassment"|awk '{for(o=1;o<=NF;o++)if($o=="bar")$o="no bar"}1'
no bar embarassment
To clear only certain parameters, you can use:
[:param1, :param2, :param3].each { |k| session.delete(k) }
Actually, this has nothing to do with the usual Windows / Unix \r\n
vs \n
issue. The TELNET procotol itself defines \r\n
as the end-of-line sequence, independently of the operating system. See RFC854.
Below is the implementation of how a function (callback API) can be converted to a promise.
function promisify(functionToExec) {
return function() {
var array = Object.values(arguments);
return new Promise((resolve, reject) => {
array.push(resolve)
try {
functionToExec.apply(null, array);
} catch (error) {
reject(error)
}
})
}
}
// USE SCENARIO
function apiFunction (path, callback) { // Not a promise
// Logic
}
var promisedFunction = promisify(apiFunction);
promisedFunction('path').then(()=>{
// Receive the result here (callback)
})
// Or use it with await like this
let result = await promisedFunction('path');
I am using MEANJS 0.6.0 with [email protected], it's good
Client:
Controller:
var input = { keyword: vm.keyword };
ProductAPi.getOrder(input)
services:
this.getOrder = function (input) {return $http.get('/api/order', { params: input });};
Server
routes
app.route('/api/order').get(products.order);
controller
exports.order = function (req, res) {
var keyword = req.query.keyword
...
public boolean isInternetWorking() {
boolean success = false;
try {
URL url = new URL("https://google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.connect();
success = connection.getResponseCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
return success;
}
return true if internet is actually available
Make sure you have these two permission
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.
android:usesCleartextTraffic="true"
If by "empty" you mean undefined
, it is the way ng-expressions are interpreted. Then, you could use :
<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>
If your system is in English, use @Rick answer:
If your system is in Brazilian Portuguese, use this:
Import:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.6/jquery.inputmask.bundle.min.js"></script>
HTML:
<input class="mask" type="text" />
JS:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"});
Its because in Brazilian Portuguese we write "1.000.000,00" and not "1,000,000.00" like in English, so if you use "." the system will not understand a decimal mark.
It is it, I hope that it help someone. I spend a lot of time to understand it.
We use a JavaScript to solve this problem; here is the source.
var buffer = 20; //scroll bar buffer
var iframe = document.getElementById('ifm');
function pageY(elem) {
return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}
function resizeIframe() {
var height = document.documentElement.clientHeight;
height -= pageY(document.getElementById('ifm'))+ buffer ;
height = (height < 0) ? 0 : height;
document.getElementById('ifm').style.height = height + 'px';
}
// .onload doesn't work with IE8 and older.
if (iframe.attachEvent) {
iframe.attachEvent("onload", resizeIframe);
} else {
iframe.onload=resizeIframe;
}
window.onresize = resizeIframe;
Note: ifm
is the iframe ID
pageY()
was created by John Resig (the author of jQuery)
To paraphrase one of my websites that does something similar:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style TYPE="text/css"><!--
.section {
_float: right;
margin-right: 210px;
_margin-right: 10px;
_width: expression( (document.body.clientWidth - 250) + "px");
}
.navbar {
margin: 10px 0;
float: right;
width: 200px;
padding: 9pt 0;
}
--></style>
</head>
<body>
<div class="navbar">
This will take up the right hand side
</div>
<div class="section">
This will fill go to the left of the "navbar" div
</div>
</body>
</html>
Eureka ! Finally I found a solution on this.
This is caused by Windows update that stops any 32-bit processes from consuming more than 1200 MB on a 64-bit machine. The only way you can repair this is by using the System Restore option on Win 7.
Start >> All Programs >> Accessories >> System Tools >> System Restore.
And then restore to a date on which your Java worked fine. This worked for me. What is surprising here is Windows still pushes system updates under the name of "Critical Updates" even when you disable all windows updates. ^&%)#* Windows :-)
I have came across the very-very-same problem.
In short:
I have made a test with ALL possible (sane) combinations of the following:
Resources/public/css
) with the CSS and a "private" directory (as Resources/assets/css
).This gave me a total of 14 combinations on the same twig, and this route was launched from
thus giving 14 x 3 = 42 tests.
Additionally, all this has been tested working in a subdirectory, so there is no way to fool by giving absolute URLs because they would simply not work.
The tests were two unnamed images and then divs named from 'a' to 'f' for the CSS built FROM the public folder and named 'g to 'l' for the ones built from the internal path.
I observed the following:
Only 3 of the 14 tests were shown adequately on the three URLs. And NONE was from the "internal" folder (Resources/assets). It was a pre-requisite to have the spare CSS PUBLIC and then build with assetic FROM there.
These are the results:
Result launched with /app_dev.php/
Result launched with /app.php/
Result launched with /
So... ONLY - The second image - Div B - Div C are the allowed syntaxes.
Here there is the TWIG code:
<html>
<head>
{% stylesheets 'bundles/commondirty/css_original/container.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: ABCDEF #}
<link href="{{ '../bundles/commondirty/css_original/a.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( 'bundles/commondirty/css_original/b.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets 'bundles/commondirty/css_original/c.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets 'bundles/commondirty/css_original/d.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/e.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/public/css_original/f.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{# First Row: GHIJKL #}
<link href="{{ '../../src/Common/DirtyBundle/Resources/assets/css/g.css' }}" rel="stylesheet" type="text/css" />
<link href="{{ asset( '../src/Common/DirtyBundle/Resources/assets/css/h.css' ) }}" rel="stylesheet" type="text/css" />
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/i.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '../src/Common/DirtyBundle/Resources/assets/css/j.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/k.css' filter="cssrewrite" %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
{% stylesheets '@CommonDirtyBundle/Resources/assets/css/l.css' %}
<link href="{{ asset_url }}" rel="stylesheet" type="text/css" />
{% endstylesheets %}
</head>
<body>
<div class="container">
<p>
<img alt="Devil" src="../bundles/commondirty/images/devil.png">
<img alt="Devil" src="{{ asset('bundles/commondirty/images/devil.png') }}">
</p>
<p>
<div class="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
C
</div>
<div class="d">
D
</div>
<div class="e">
E
</div>
<div class="f">
F
</div>
</p>
<p>
<div class="g">
G
</div>
<div class="h">
H
</div>
<div class="i">
I
</div>
<div class="j">
J
</div>
<div class="k">
K
</div>
<div class="l">
L
</div>
</p>
</div>
</body>
</html>
The container.css:
div.container
{
border: 1px solid red;
padding: 0px;
}
div.container img, div.container div
{
border: 1px solid green;
padding: 5px;
margin: 5px;
width: 64px;
height: 64px;
display: inline-block;
vertical-align: top;
}
And a.css, b.css, c.css, etc: all identical, just changing the color and the CSS selector.
.a
{
background: red url('../images/devil.png');
}
The "directories" structure is:
Directories
All this came, because I did not want the individual original files exposed to the public, specially if I wanted to play with "less" filter or "sass" or similar... I did not want my "originals" published, only the compiled one.
But there are good news. If you don't want to have the "spare CSS" in the public directories... install them not with --symlink
, but really making a copy. Once "assetic" has built the compound CSS, and you can DELETE the original CSS from the filesystem, and leave the images:
Compilation process
Note I do this for the --env=prod
environment.
Just a few final thoughts:
This desired behaviour can be achieved by having the images in "public" directory in Git or Mercurial and the "css" in the "assets" directory. That is, instead of having them in "public" as shown in the directories, imagine a, b, c... residing in the "assets" instead of "public", than have your installer/deployer (probably a Bash script) to put the CSS temporarily inside the "public" dir before assets:install
is executed, then assets:install
, then assetic:dump
, and then automating the removal of CSS from the public directory after assetic:dump
has been executed. This would achive EXACTLY the behaviour desired in the question.
Another (unknown if possible) solution would be to explore if "assets:install" can only take "public" as the source or could also take "assets" as a source to publish. That would help when installed with the --symlink
option when developing.
Additionally, if we are going to script the removal from the "public" dir, then, the need of storing them in a separate directory ("assets") disappears. They can live inside "public" in our version-control system as there will be dropped upon deploy to the public. This allows also for the --symlink
usage.
BUT ANYWAY, CAUTION NOW: As now the originals are not there anymore (rm -Rf
), there are only two solutions, not three. The working div "B" does not work anymore as it was an asset() call assuming there was the original asset. Only "C" (the compiled one) will work.
So... there is ONLY a FINAL WINNER: Div "C" allows EXACTLY what it was asked in the topic: To be compiled, respect the path to the images and do not expose the original source to the public.
The winner is C
I don´t know if this is relevant anymore, but I fixed it with the @RequestMapping annotation.
@RequestMapping(method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
++[[]][+[]] => 1 // [+[]] = [0], ++0 = 1
[+[]] => [0]
Then we have a string concatenation
1+[0].toString() = 10
You can also use awk
for these purposes, since it allows you to perform more complex checks in a clearer way:
Lines not containing foo
:
awk '!/foo/'
Lines containing neither foo
nor bar
:
awk '!/foo/ && !/bar/'
Lines containing neither foo
nor bar
which contain either foo2
or bar2
:
awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'
And so on.
Well i have the same problem, my way to fix it was to stop and disable the "application experience" service in Windows.
You are not calling the function inner
, just defining it.
function outer() {
function inner() {
alert("hi");
}
inner(); //Call the inner function
}
What you want is a type of software called a "Disassembler".
Quick google yields this: Link
To check whether postfix is running or not
sudo postfix status
If it is not running, start it.
sudo postfix start
Then telnet to localhost port 25 to test the email id
ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix
Hi,
Are you there?
regards,
Admin
.
Do not forget the . at the end, which indicates end of line
Seems question is not about strings equality, but of sets equality. You can compare them this way only by splitting strings and converting them to sets:
s1 = 'abc def ghi'
s2 = 'def ghi abc'
set1 = set(s1.split(' '))
set2 = set(s2.split(' '))
print set1 == set2
Result will be
True
You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;
package main
import (
"fmt"
"encoding/json"
)
type Data struct {
Votes *Votes `json:"votes"`
Count string `json:"count,omitempty"`
}
type Votes struct {
OptionA string `json:"option_A"`
}
func main() {
s := `{ "votes": { "option_A": "3" } }`
data := &Data{
Votes: &Votes{},
}
err := json.Unmarshal([]byte(s), data)
fmt.Println(err)
fmt.Println(data.Votes)
s2, _ := json.Marshal(data)
fmt.Println(string(s2))
data.Count = "2"
s3, _ := json.Marshal(data)
fmt.Println(string(s3))
}
https://play.golang.org/p/ScuxESTW5i
Based on your most recent comment you could address that by using an interface{}
to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{}
which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.
The "nav nav-list" class of Twiter Bootstrap 2.0 is handy for building a side bar.
You can see a lot of documentation at http://www.w3resource.com/twitter-bootstrap/nav-tabs-and-pills-tutorial.php
From the numpy fft page http://docs.scipy.org/doc/numpy/reference/routines.fft.html:
When the input a is a time-domain signal and A = fft(a), np.abs(A) is its amplitude spectrum and np.abs(A)**2 is its power spectrum. The phase spectrum is obtained by np.angle(A).