Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
This is the normal behavior and the reason is that your sqlCommandHandlerService.persist
method needs a TX when being executed (because it is marked with @Transactional
annotation). But when it is called inside processNextRegistrationMessage
, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist
method, it causes TX to be set to rollBackOnly
(even if you catch the exception in the caller and ignore it).
To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.
Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.
I can give you two advices:
Try this, assuming you're on Spring 3.1:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
Replace 3.1
on the last line with whatever major Spring version you use. Meaning: there is no 3.1.1
XSD even though there is a Spring version 3.1.1
.
Are you extending ListActivity?
If so, put a circular progress dialog with the following line in your xml
<ProgressBar
android:id="@android:id/empty"
...other stuff...
/>
Now, the progress indicator will show up till you have all your listview information, and set the Adapter. At which point, it will go back to the listview, and the progress bar will go away.
Agreed with the answer from sll, but experienced another hurdle which was having specified a namespace in the attributes, when receiving the return xml that namespace wasn't included and thus failed finding the class.
i had to find a workaround to specifying the namespace in the attribute and it worked.
ie.
[Serializable()]
[XmlRoot("Patient", Namespace = "http://www.xxxx.org/TargetNamespace")]
public class Patient
generated
<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xxxx.org/TargetNamespace">
but I had to change it to
[Serializable()]
[XmlRoot("Patient")]
public class Patient
which generated to
<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
This solved my problem, hope it helps someone else.
You are trying to load a XIB named DetailViewController
, but no such XIB exists or it's not member of your current target.
Nurik's answer was very helpful, but I couldn't get it to work until I found this. In short, if you're using the compatibility library (eg SupportFragmentManager instead of FragmentManager), the syntax of the XML animation files will be different.
XStream!
Updated: I added unmarshal part as requested in comments..
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("name","chris");
map.put("island","faranga");
XStream magicApi = new XStream();
magicApi.registerConverter(new MapEntryConverter());
magicApi.alias("root", Map.class);
String xml = magicApi.toXML(map);
System.out.println("Result of tweaked XStream toXml()");
System.out.println(xml);
Map<String, String> extractedMap = (Map<String, String>) magicApi.fromXML(xml);
assert extractedMap.get("name").equals("chris");
assert extractedMap.get("island").equals("faranga");
}
public static class MapEntryConverter implements Converter {
public boolean canConvert(Class clazz) {
return AbstractMap.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
AbstractMap map = (AbstractMap) value;
for (Object obj : map.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
writer.startNode(entry.getKey().toString());
Object val = entry.getValue();
if ( null != val ) {
writer.setValue(val.toString());
}
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Map<String, String> map = new HashMap<String, String>();
while(reader.hasMoreChildren()) {
reader.moveDown();
String key = reader.getNodeName(); // nodeName aka element's name
String value = reader.getValue();
map.put(key, value);
reader.moveUp();
}
return map;
}
}
}
What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:
public static string ConvertToNewKey(string oldPrivateKey)
{
// get the current container name from the database...
rsa.PersistKeyInCsp = false;
rsa.Clear();
rsa = null;
string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...
// re-encrypt existing data to use the new keys and write to database...
return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
string containerName = DateTime.Now.Ticks.ToString();
// create the new key...
// saves container name and public key to database...
// and returns Private Key XML.
}
before creating the new key.
In my case; my WCF service function was using List<byte> Types
parameter and i was getting this exception in the client side. Then i changed it to byte[] Types
, updated service reference and problem is solved.
Let me re-word that question for your by filling in the definitions.
Or, to put in more completely, If I want to call a method without an instance, but knowing the class, how can I have it resolved based upon the instance that I don't have.
Sure you can. Eg.
<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
Output
<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
<content type="latest"/>
</news>
Have fun.
To use unsafe code blocks, open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox, then compile and run.
class myclass
{
public static void Main(string[] args)
{
unsafe
{
int iData = 10;
int* pData = &iData;
Console.WriteLine("Data is " + iData);
Console.WriteLine("Address is " + (int)pData);
}
}
}
Output:
Data is 10
Address is 1831848
const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;
If you are to encounter the error that says Microsoft.CSharp.Core.targets not found
, these are the steps I took to correct mine:
Open any previous working projects folder and navigate to the link showed in the error, that is Projects/(working project name)/packages/Microsoft.Net.Compilers.1.3.2/tools/
and search for Microsoft.CSharp.Core.targets
file.
Copy this file and put it in the non-working project tools folder
(that is, navigating to the tools folder in the non-working project as shown above)
Now close your project (if it was open) and reopen it.
It should be working now.
Also, to make sure everything is working properly in your now open Visual Studio Project, Go to Tools > NuGetPackage Manager > Manage NuGet Packages For Solution
. Here, you might find an error that says, CodeAnalysis.dll is being used by another application.
Again, go to the tools folder
, find the specified file and delete it. Come back to Manage NuGet Packages For Solution
. You will find a link that will ask you to Reload, click it and everything gets re-installed.
Your project should be working properly now.
If you're trying to insert in to last_accessed_on
, which is a DateTime2
, then your issue is with the fact that you are converting it to a varchar
in a format that SQL doesn't understand.
If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:
UPDATE student_queues
SET Deleted=0,
last_accessed_by='raja',
last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
Or if you want to use CAST
, replace with:
CAST('2014-07-23 09:37:00.000' AS datetime2)
This is using the SQL ISO Date Format.
Another pure BASH way:
> s='/some/random/file.csv:some string'
> echo "${s%%:*}"
/some/random/file.csv
In JavaScript try:
encodeURIComponent()
and in PHP:
urldecode($_POST['field']);
HEAD is short for current branch so git push -u origin HEAD works. Now to avoid this typing everytime I use alias:
git config --global alias.pp 'push -u origin HEAD'
After this, everytime I want to push branch created via git -b branch I can push it using:
git pp
Hope this saves time for someone!
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect
:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn
from the console by doing this:
indirect("imported_fn()");
Using eval
was my first thought, but it doesn't work. My hypothesis is that calling eval
from the console remains in the context of console, and we need to execute in the context of the module.
I know this is an old question, with quite a few answers, but I was surprised to find that no one was suggesting the naming convention used in the official documentation:
$ docker build -f dockerfiles/Dockerfile.debug -t myapp_debug . $ docker build -f dockerfiles/Dockerfile.prod -t myapp_prod .
The above commands will build the current build context (as specified by the
.
) twice, once using a debug version of aDockerfile
and once using a production version.
In summary, if you have a file called Dockerfile
in the root of your build context it will be automatically picked up. If you need more than one Dockerfile
for the same build context, the suggested naming convention is:
Dockerfile.<purpose>
These dockerfiles could be in the root of your build context or in a subdirectory to keep your root directory more tidy.
Given a root Vue instance is accessible by all descendants via this.$root
, a parent component can access child components via the this.$children
array, and a child component can access it's parent via this.$parent
, your first instinct might be to access these components directly.
The VueJS documentation warns against this specifically for two very good reasons:
The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:
$on()
- allows you to declare a listener on your Vue instance with which to listen to events$emit()
- allows you to trigger events on the same instance (self)$on()
and $emit()
:const events = new Vue({}),_x000D_
parentComponent = new Vue({_x000D_
el: '#parent',_x000D_
ready() {_x000D_
events.$on('eventGreet', () => {_x000D_
this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;_x000D_
});_x000D_
},_x000D_
data: {_x000D_
parentMsg: 'I am listening for an event..',_x000D_
counter: 0_x000D_
}_x000D_
}),_x000D_
childComponent = new Vue({_x000D_
el: '#child',_x000D_
methods: {_x000D_
greet: function () {_x000D_
events.$emit('eventGreet');_x000D_
this.childMsg = `I am firing greeting event ${++this.counter} times..`;_x000D_
}_x000D_
},_x000D_
data: {_x000D_
childMsg: 'I am getting ready to fire an event.',_x000D_
counter: 0_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script>_x000D_
_x000D_
<div id="parent">_x000D_
<h2>Parent Component</h2>_x000D_
<p>{{parentMsg}}</p>_x000D_
</div>_x000D_
_x000D_
<div id="child">_x000D_
<h2>Child Component</h2>_x000D_
<p>{{childMsg}}</p>_x000D_
<button v-on:click="greet">Greet</button>_x000D_
</div>
_x000D_
Answer taken from the original post: Communicating between components in VueJS
These paradigms don't have to be mutually exclusive. If you look at python, it supports functions and classes, but at the same time, everything is an object, including functions. You can mix and match functional/oop/procedural style all in one piece of code.
What I mean is, in functional languages (at least in Haskell, the only one I studied) there are no statements! functions are only allowed one expression inside them!! BUT, functions are first-class citizens, you can pass them around as parameters, along with a bunch of other abilities. They can do powerful things with few lines of code.
While in a procedural language like C, the only way you can pass functions around is by using function pointers, and that alone doesn't enable many powerful tasks.
In python, a function is a first-class citizen, but it can contain arbitrary number of statements. So you can have a function that contains procedural code, but you can pass it around just like functional languages.
Same goes for OOP. A language like Java doesn't allow you to write procedures/functions outside of a class. The only way to pass a function around is to wrap it in an object that implements that function, and then pass that object around.
In Python, you don't have this restriction.
Try this:
SET @birthday = CAST('1980-05-01' AS DATE);
SET @today = CURRENT_DATE();
SELECT YEAR(@today) - YEAR(@birthday) -
(CASE WHEN
MONTH(@birthday) > MONTH(@today) OR
(MONTH(@birthday) = MONTH(@today) AND DAY(@birthday) > DAY(@today))
THEN 1
ELSE 0
END);
It returns this year - birth year (how old the person will be this year after the birthday) and adjusts based on whether the person has had the birthday yet this year.
It doesn't suffer from the rounding errors of other methods presented here.
Freely adapted from here
Assuming userInfoList
is a List<UserInfo>
:
var groups = userInfoList
.GroupBy(n => n.metric)
.Select(n => new
{
MetricName = n.Key,
MetricCount = n.Count()
}
)
.OrderBy(n => n.MetricName);
The lambda function for GroupBy()
, n => n.metric
means that it will get field metric
from every UserInfo
object encountered. The type of n
is depending on the context, in the first occurrence it's of type UserInfo
, because the list contains UserInfo
objects. In the second occurrence n
is of type Grouping
, because now it's a list of Grouping
objects.
Grouping
s have extension methods like .Count()
, .Key()
and pretty much anything else you would expect. Just as you would check .Lenght
on a string
, you can check .Count()
on a group.
Use grep
$ grep --help | grep -i context
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
Use the "import android.app.AlertDialog;
" import and then you write
String[] items = {"...","...."};
AlertDialog.Builder build = new AlertDialog.Builder(context);
build.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//do stuff....
}
}).create().show();
If you are really worried about undefined being redefined, you can protect against this with some helper method like this:
function is_undefined(value) {
var undefined_check; // instantiate a new variable which gets initialized to the real undefined value
return value === undefined_check;
}
This works because when someone writes undefined = "foo"
he only lets the name undefined
reference to a new value, but he doesn't change the actual value of undefined
.
It's not much of an answer, but you might need to go old school and capture an image snapshot of the IIS process and debug it. You might also want to check out Tess Ferrandez's blog - she is a kick a** microsoft escalation engineer and her blog focuses on debugging windows ASP.NET, but the blog is relevant to windows debugging in general. If you select the ASP.NET tag (which is what I've linked to) then you'll see several items that are similar.
The following will return true if the JTextField "name" does not contain text:
name.getText().isEmpty
Remember that you will need to connect to running docker container. So you probably want to use tcp instead of unix socket. Check output of docker ps
command and look for running mysql containers. If you find one then use mysql command like this: mysql -h 127.0.0.1 -P <mysql_port>
(you will find port in docker ps
output).
If you can't find any running mysql container in docker ps
output then try docker images
to find mysql image name and try something like this to run it:
docker run -d -p 3306:3306 tutum/mysql
where "tutum/mysql" is image name found in docker images
.
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
You could use actionLayout
from the support library.
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/button_item"
android:title=""
app:actionLayout="@layout/button_layout"
app:showAsAction="always"
/>
</menu>
button_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Activity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.button_item);
Button btn = item.getActionView().findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Toolbar Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
return true;
}
Variant: I have an icon with id="logo" at the top left of the main page; a spinner gif is then overlaid on top (with transparency) when ajax is working.
jQuery.ajaxSetup({
beforeSend: function() {
$('#logo').css('background', 'url(images/ajax-loader.gif) no-repeat')
},
complete: function(){
$('#logo').css('background', 'none')
},
success: function() {}
});
With the cursor on the class name declaration I do ALT + Return and my Intellij 14.1.4 offers me a popup with the option to 'Create Test'.
Well, using the static Drawable.createFromPath(String pathName)
seems a bit more straightforward to me than decoding it yourself... :-)
If your mImg
is a simple ImageView
, you don't even need it, use mImg.setImageUri(Uri uri)
directly.
I just had the same question but with irregularly spaced datapoints. Resample is not really an option here. So I created my own function. Maybe it will be useful for others too:
from pandas import Series, DataFrame
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
def rolling_mean(data, window, min_periods=1, center=False):
''' Function that computes a rolling mean
Parameters
----------
data : DataFrame or Series
If a DataFrame is passed, the rolling_mean is computed for all columns.
window : int or string
If int is passed, window is the number of observations used for calculating
the statistic, as defined by the function pd.rolling_mean()
If a string is passed, it must be a frequency string, e.g. '90S'. This is
internally converted into a DateOffset object, representing the window size.
min_periods : int
Minimum number of observations in window required to have a value.
Returns
-------
Series or DataFrame, if more than one column
'''
def f(x):
'''Function to apply that actually computes the rolling mean'''
if center == False:
dslice = col[x-pd.datetools.to_offset(window).delta+timedelta(0,0,1):x]
# adding a microsecond because when slicing with labels start and endpoint
# are inclusive
else:
dslice = col[x-pd.datetools.to_offset(window).delta/2+timedelta(0,0,1):
x+pd.datetools.to_offset(window).delta/2]
if dslice.size < min_periods:
return np.nan
else:
return dslice.mean()
data = DataFrame(data.copy())
dfout = DataFrame()
if isinstance(window, int):
dfout = pd.rolling_mean(data, window, min_periods=min_periods, center=center)
elif isinstance(window, basestring):
idx = Series(data.index.to_pydatetime(), index=data.index)
for colname, col in data.iterkv():
result = idx.apply(f)
result.name = colname
dfout = dfout.join(result, how='outer')
if dfout.columns.size == 1:
dfout = dfout.ix[:,0]
return dfout
# Example
idx = [datetime(2011, 2, 7, 0, 0),
datetime(2011, 2, 7, 0, 1),
datetime(2011, 2, 7, 0, 1, 30),
datetime(2011, 2, 7, 0, 2),
datetime(2011, 2, 7, 0, 4),
datetime(2011, 2, 7, 0, 5),
datetime(2011, 2, 7, 0, 5, 10),
datetime(2011, 2, 7, 0, 6),
datetime(2011, 2, 7, 0, 8),
datetime(2011, 2, 7, 0, 9)]
idx = pd.Index(idx)
vals = np.arange(len(idx)).astype(float)
s = Series(vals, index=idx)
rm = rolling_mean(s, window='2min')
There are several methods, two of which are as follows. Provide a custom installer or a setup project.
Here is how to create a custom installer
[RunInstaller(true)]
public class MyInstaller : Installer
{
public HelloInstaller()
: base()
{
}
public override void Commit(IDictionary mySavedState)
{
base.Commit(mySavedState);
System.IO.File.CreateText("Commit.txt");
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
System.IO.File.CreateText("Install.txt");
}
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
File.Delete("Commit.txt");
File.Delete("Install.txt");
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
File.Delete("Install.txt");
}
}
To add a setup project
Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment
Set properties of the project, using the properties window
The article How to create a Setup package by using Visual Studio .NET provides the details.
In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using @RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore
instead of org.codehaus.jackson.annotate.JsonIgnore
, as otherwise, it simply did nothing.
I prefer this way, not using a cell but a range
Dim cell_to_test As Range, cells_changed As Range
Set cells_changed = Target(1, 1)
Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )
If Not Intersect(cells_changed, cell_to_test) Is Nothing Then
Macro
End If
A better pyramid can be printed this way:
The Pattern is $ $$$ $$$$$ $$$$$$$ $$$$$$$$$ $$$$$$$$$$$
public static void main(String agrs[]) {
System.out.println("The Pattern is");
int size = 11; //use only odd numbers here
for (int i = 1; i <= size; i=i+2) {
int spaceCount = (size - i)/2;
for(int j = 0; j< size; j++) {
if(j < spaceCount || j >= (size - spaceCount)) {
System.out.print(" ");
} else {
System.out.print("$");
}
}
System.out.println();
}
}
Here in my sample I find out the solution of this, because I had the same problem with updates and subquerys:
UPDATE
A
SET
A.ValueToChange = B.NewValue
FROM
(
Select * From C
) B
Where
A.Id = B.Id
Maybe the 40 bytes fits into the pipe buffer, and the 40000 bytes doesn't?
Edit:
The sending process is sent a SIGPIPE signal when you try to write to a closed pipe. I don't know exactly when the signal is sent, or what effect the pipe buffer has on this. You may be able to recover by trapping the signal with the sigaction call.
To answer the original question: here is how you decode utf-8 in javascript:
http://ecmanaut.blogspot.ca/2006/07/encoding-decoding-utf8-in-javascript.html
Specifically,
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
We have been using this in our production code for 6 years, and it has worked flawlessly.
Note, however, that escape() and unescape() are deprecated. See this.
You can find all of those operators in the Python language reference, though you'll have to scroll around a bit to find them all. As other answers have said:
**
operator does exponentiation. a ** b
is a
raised to the b
power. The same **
symbol is also used in function argument and calling notations, with a different meaning (passing and receiving arbitrary keyword arguments).^
operator does a binary xor. a ^ b
will return a value with only the bits set in a
or in b
but not both. This one is simple!%
operator is mostly to find the modulus of two integers. a % b
returns the remainder after dividing a
by b
. Unlike the modulus operators in some other programming languages (such as C), in Python a modulus it will have the same sign as b
, rather than the same sign as a
. The same operator is also used for the "old" style of string formatting, so a % b
can return a string if a
is a format string and b
is a value (or tuple of values) which can be inserted into a
.//
operator does Python's version of integer division. Python's integer division is not exactly the same as the integer division offered by some other languages (like C), since it rounds towards negative infinity, rather than towards zero. Together with the modulus operator, you can say that a == (a // b)*b + (a % b)
. In Python 2, floor division is the default behavior when you divide two integers (using the normal division operator /
). Since this can be unexpected (especially when you're not picky about what types of numbers you get as arguments to a function), Python 3 has changed to make "true" (floating point) division the norm for division that would be rounded off otherwise, and it will do "floor" division only when explicitly requested. (You can also get the new behavior in Python 2 by putting from __future__ import division
at the top of your files. I strongly recommend it!)WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL '-3' DAY);
use quotes on the -3 value
This is an ES6 function which removes duplicates from an array of objects, filtering by the specified object property
function dedupe(arr = [], fnCheck = _ => _) {
const set = new Set();
let len = arr.length;
for (let i = 0; i < len; i++) {
const primitive = fnCheck(arr[i]);
if (set.has(primitive)) {
// duplicate, cut it
arr.splice(i, 1);
i--;
len--;
} else {
// new item, add it
set.add(primitive);
}
}
return arr;
}
const test = [
{video:{slug: "a"}},
{video:{slug: "a"}},
{video:{slug: "b"}},
{video:{slug: "c"}},
{video:{slug: "c"}}
]
console.log(dedupe(test, x => x.video.slug));
// [{video:{slug: "a"}}, {video:{slug: "b"}}, {video:{slug: "c"}}]
Try this simple program:
public class HashMapGetKey {
public static void main(String args[]) {
// create hash map
HashMap map = new HashMap();
// populate hash map
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
// get keyset value from map
Set keyset=map.keySet();
// check key set values
System.out.println("Key set values are: " + keyset);
}
}
You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile
g++ -std=c++0x *.cpp -o output
This is not possible from HTML on. The closest what you can get is the accept-charset
attribute of the <form>
. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type
header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.
To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding
attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).
Update:
Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type
header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.
ASP.NET HTML Encode - short and sweet:
public static string ToHtmlEncodedString(this string s)
{
if (String.IsNullOrEmpty(s))
return s;
return HttpUtility.HtmlEncode(s);
}
The Prefix function is definitely the most efficient way of solving this problem, but you can also use for-in loops like the following:
let array = [1,2,3,4,5,6,7,8,9]
let maxNum = 5
var iterationNumber = 0
var firstNumbers = [Int()]
if array.count > maxNum{
for i in array{
iterationNumber += 1
if iterationNumber <= maxNum{
firstNumbers.append(i)
}
}
firstNumbers.remove(at: 0)
print(firstNumbers)
} else {
print("There were not \(maxNum) items in the array.")
}
This solution takes up many lines of code but checks to see if there are enough items in the array to carry out the program, then continues and solves the problem.
This solution uses many basic functions including array.count
, which returns the amount of items in the array, not the position of last item in the array. It also uses array.append
, which adds things onto the end of the array. Lastly, it uses array.remove
, which removes the array's item that has a specified position.
I have tested it it and it works for at least swift 5.
I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.
HTML Code:
<body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>
CSS Code:
#dt{text-indent: -500px;height:25px; width:200px;}
Javascript Code :
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}
Output:
Matt has shown one classic modification of the close button.
The other is to have the close button minimize the window.
You can reproduced this behavior by having the iconify method
be the protocol method's second argument.
Here's a working example, tested on Windows 7 & 10:
# Python 3
import tkinter
import tkinter.scrolledtext as scrolledtext
root = tkinter.Tk()
# make the top right close button minimize (iconify) the main window
root.protocol("WM_DELETE_WINDOW", root.iconify)
# make Esc exit the program
root.bind('<Escape>', lambda e: root.destroy())
# create a menu bar with an Exit command
menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
# create a Text widget with a Scrollbar attached
txt = scrolledtext.ScrolledText(root, undo=True)
txt['font'] = ('consolas', '12')
txt.pack(expand=True, fill='both')
root.mainloop()
In this example we give the user two new exit options:
the classic File ? Exit, and also the Esc button.
class Example extends React.Component {
render() {
return <h1>{this.props.text}</h1>;
}
}
Example.defaultProps = { text: 'yo' };
Basically, you write a pipe which you can then use in the *ngFor
directive.
In your component:
filterargs = {title: 'hello'};
items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];
In your template, you can pass string, number or object to your pipe to use to filter on:
<li *ngFor="let item of items | myfilter:filterargs">
In your pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myfilter',
pure: false
})
export class MyFilterPipe implements PipeTransform {
transform(items: any[], filter: Object): any {
if (!items || !filter) {
return items;
}
// filter items array, items which match and return true will be
// kept, false will be filtered out
return items.filter(item => item.title.indexOf(filter.title) !== -1);
}
}
Remember to register your pipe in app.module.ts
; you no longer need to register the pipes in your @Component
import { MyFilterPipe } from './shared/pipes/my-filter.pipe';
@NgModule({
imports: [
..
],
declarations: [
MyFilterPipe,
],
providers: [
..
],
bootstrap: [AppComponent]
})
export class AppModule { }
Here's a Plunker which demos the use of a custom filter pipe and the built-in slice pipe to limit results.
Please note (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular.
Possible Solution for Web Apps: While zooming can not be disabled in iOS Safari anymore, it will be disabled when opening the site from a home screen shortcut.
Add these meta tags to declare your App as "Web App capable":
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" >
<meta name="apple-mobile-web-app-capable" content="yes" >
However only use this feature if your app is self sustaining, as the forward/backward buttons and URL bar as well as the sharing options are disabled. (You can still swipe left and right though) This approach however enables quite the app like ux. The fullscreen browser only starts when the site is loaded from the homescreen. I also only got it to work after I included an apple-touch-icon-180x180.png in my root folder.
As a bonus, you probably also want to include a variant of this as well:
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
On mousedown, start set the state, if the mousemove event is fired record it, finally on mouseup, check if the mouse moved. If it moved, we've been dragging. If we've not moved, it's a click.
var isDragging = false;
$("a")
.mousedown(function() {
isDragging = false;
})
.mousemove(function() {
isDragging = true;
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
if (!wasDragging) {
$("#throbble").toggle();
}
});
Here's a demo: http://jsfiddle.net/W7tvD/1399/
In my case, writing a small utility in C# helped. Links that helped me - http://pascallaurin42.blogspot.com/2012/05/tfs-queries-searching-in-all-files-of.html
How to list files of a team project using tfs api?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Framework.Client;
using System.IO;
namespace TFSSearch
{
class Program
{
static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" }; //Text to search
static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html",
"*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions
static void Main(string[] args)
{
try
{
var tfs = TfsTeamProjectCollectionFactory
.GetTeamProjectCollection(new Uri("http://{tfsserver}:8080/tfs/}")); // one some servers you also need to add collection path (if it not the default collection)
tfs.EnsureAuthenticated();
var versionControl = tfs.GetService<VersionControlServer>();
StreamWriter outputFile = new StreamWriter(@"C:\Find.txt");
var allProjs = versionControl.GetAllTeamProjects(true);
foreach (var teamProj in allProjs)
{
foreach (var filePattern in filePatterns)
{
var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
.Where(i => !i.ServerItem.Contains("_ReSharper")); //skipping resharper stuff
foreach (var item in items)
{
List<string> lines = SearchInFile(item);
if (lines.Count > 0)
{
outputFile.WriteLine("FILE:" + item.ServerItem);
outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
outputFile.WriteLine();
}
foreach (string line in lines)
{
outputFile.WriteLine(line);
}
if (lines.Count > 0)
{
outputFile.WriteLine();
}
}
}
outputFile.Flush();
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
Console.WriteLine("========");
Console.Read();
}
// Define other methods and classes here
private static List<string> SearchInFile(Item file)
{
var result = new List<string>();
try
{
var stream = new StreamReader(file.DownloadFile(), Encoding.Default);
var line = stream.ReadLine();
var lineIndex = 0;
while (!stream.EndOfStream)
{
if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
result.Add("=== Line " + lineIndex + ": " + line.Trim());
line = stream.ReadLine();
lineIndex++;
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
return result;
}
}
}
All you need:
table {
border-collapse: separate;
border-spacing: 0 1em;
}
That assumes you want a 1em vertical gap, and no horizontal gap. If you're doing this, you should probably also look at controlling your line-height.
Sort of weird that some of the answers people gave involve border-collapse: collapse, whose effect is the exact opposite of what the question asked for.
GroupBy using in Hibernate
This is the resulting code
public Map getStateCounts(final Collection ids) {
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for (Object[] obj : results) {
DownloadState downloadState = (DownloadState) obj[0];
stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
}
hibernateSession.closeSession();
return stateMap;
}
try {
SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
// or
SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format
java.util.Date d1 =(java.util.Date)format.parse(your_Time);
java.sql.Time ppstime = new java.sql.Time(d1.getTime());
} catch(Exception e) {
Log.e("Exception is ", e.toString());
}
If you are using SourceTree (I'm using 2.4.1), I found a simpler way to generate an SSH key and add it to my Bitbucket settings. This solved the problem for me.
I received a confirmation email from Bitbucket that an SSH key had been added to my account.
For reference, on macOS, using Terminal, you can use the following command to see the keys generated for your device. This is where the key you generated is stored.
ls -la ~/.ssh
As others have stated, this documentation helped me: Use the SSH protocol with Bitbucket Cloud
You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.
If you don't use the onLocationChanged it always will be the old location.
Add android:onClick="clickEvent" to your image view.
<ImageView android:id="@+id/favorite_icon"
android:src="@drawable/small_star"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right" android:paddingTop="63sp"
android:paddingRight="2sp"
android:onClick="clickEvent" />
In your activity you can create a method with the same name (clickEvent(View v)), and that's it! You can see the log and the toast text too.
public void clickEvent(View v)
{
Log.i(SystemSettings.APP_TAG + " : " + HomeActivity.class.getName(), "Entered onClick method");
Toast.makeText(v.getContext(),
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
}
Modern string formatting:
"{} and {}".format("string", 1)
The following code can be compiled and runs properly, using MinGW G++ 3.4.5 on Window 7:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class A{
public:
virtual void func1(const T& p)
{
cout<<"A:"<<p<<endl;
}
};
template <typename T>
class B
: public A<T>
{
public:
virtual void func1(const T& p)
{
cout<<"A<--B:"<<p<<endl;
}
};
int main(int argc, char** argv)
{
A<string> a;
B<int> b;
B<string> c;
A<string>* p = &a;
p->func1("A<string> a");
p = dynamic_cast<A<string>*>(&c);
p->func1("B<string> c");
B<int>* q = &b;
q->func1(3);
}
and the output is:
A:A<string> a
A<--B:B<string> c
A<--B:3
And later I added a new class X:
class X
{
public:
template <typename T>
virtual void func2(const T& p)
{
cout<<"C:"<<p<<endl;
}
};
When I tried to use class X in main() like this:
X x;
x.func2<string>("X x");
g++ report the following error:
vtempl.cpp:34: error: invalid use of `virtual' in template declaration of `virtu
al void X::func2(const T&)'
So it is obvious that:
[System.Net.Dns]::GetHostByName('remotehost').HostName
The "contains" method searched for whether the list contains an entry that returns true from Customer.equals(Object o). If you have not overridden equals(Object) in Customer or one of its parents then it will only search for an existing occurrence of the same object. It may be this was what you wanted, in which case your code should work. But if you were looking for not having two objects both representing the same customer, then you need to override equals(Object) to return true when that is the case.
It is also true that using one of the implementations of Set instead of List would give you duplicate removal automatically, and faster (for anything other than very small Lists). You will still need to provide code for equals.
You should also override hashCode() when you override equals().
for this small example:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print (data);
mysock.close()
adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem
unplug not necessary,just uninstall your port,restart and install driver again.you will see arduino COM port under the LPT & PORT section.
The difference between Response.Write()
and Response.Output.Write()
in ASP.NET. The short answer is that the latter gives you String.Format-style
output and the former doesn't. The long answer follows.
In ASP.NET the Response
object is of type HttpResponse
and when you say Response.Write
you're really saying (basically) HttpContext.Current.Response.Write
and calling one of the many overloaded Write
methods of HttpResponse
.
Response.Write
then calls .Write()
on it's internal TextWriter
object:
public void Write(object obj){ this._writer.Write(obj);}
HttpResponse
also has a Property called Output
that is of type, yes, TextWriter
, so:
public TextWriter get_Output(){ return this._writer; }
Which means you can do the Response
whatever a TextWriter
will let you. Now, TextWriters support a Write()
method aka String.Format
, so you can do this:
Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);
But internally, of course, this is happening:
public virtual void Write(string format, params object[] arg)
{
this.Write(string.Format(format, arg));
}
It's just two lines of code if LINQ is allowed to use. Please see my answer here.
EDIT
Here is my generic function which can return all the permutations (not combinations) from a list of T:
static IEnumerable<IEnumerable<T>>
GetPermutations<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutations(list, length - 1)
.SelectMany(t => list.Where(e => !t.Contains(e)),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
Example:
IEnumerable<IEnumerable<int>> result =
GetPermutations(Enumerable.Range(1, 3), 3);
Output - a list of integer-lists:
{1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1}
As this function uses LINQ so it requires .net 3.5 or higher.
The easiest way would be
Section = 'Sec_' + Section
But for efficiency, see: https://waymoot.org/home/python_string/
If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");
// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
I had this error aswell.
I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.
This will solve my “SMTP Error: Could not authenticate” in PHPMailer error.
In this case both strconv
and fmt.Sprintf
do the same job but using the strconv
package's Itoa
function is the best choice, because fmt.Sprintf
allocate one more object during conversion.
check the benchmark here: https://gist.github.com/evalphobia/caee1602969a640a4530
see https://play.golang.org/p/hlaz_rMa0D for example.
I'm using WAS ND 7.0
My JVM need all the following arguments to be monitored in JConsole
-Djavax.management.builder.initial=
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=8855
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
JIT compiler only compiles the byte-code to equivalent native code at first execution. Upon every successive execution, the JVM merely uses the already compiled native code to optimize performance.
Without JIT compiler, the JVM interpreter translates the byte-code line-by-line to make it appear as if a native application is being executed.
I just had the same problem and ended up doing:
git rebase -i HEAD~N
(N is the number of commits git will show you)
That prompts your text editor and then you can remove the commit you want by deleting the line associated with it.
You need to tell it that you are using SSL:
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
In case you miss anything, here is working code:
String d_email = "[email protected]",
d_uname = "Name",
d_password = "urpassword",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Indoors Readable File: " + params[0].getName(),
m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
try {
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport transport = session.getTransport("smtps");
transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
fix json values, it's add \ before u{xxx} to all +" "
$item = preg_replace_callback('/"(.+?)":"(u.+?)",/', function ($matches) {
$matches[2] = preg_replace('/(u)/', '\u', $matches[2]);
$matches[2] = preg_replace('/(")/', '"', $matches[2]);
$matches[2] = json_decode('"' . $matches[2] . '"');
return '"' . $matches[1] . '":"' . $matches[2] . '",';
}, $item);
Examples of jersey Rest client :
Adding dependency :
<!-- jersey -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
ForGetMethod and passing two parameter :
Client client = Client.create();
WebResource webResource1 = client
.resource("http://localhost:10102/NewsTickerServices/AddGroup/"
+ userN + "/" + groupName);
ClientResponse response1 = webResource1.get(ClientResponse.class);
System.out.println("responser is" + response1);
GetMethod passing one parameter and Getting a Respone of List :
Client client = Client.create();
WebResource webResource1 = client
.resource("http://localhost:10102/NewsTickerServices/GetAssignedUser/"+grpName);
//value changed
String response1 = webResource1.type(MediaType.APPLICATION_JSON).get(String.class);
List <String > Assignedlist =new ArrayList<String>();
JSONArray jsonArr2 =new JSONArray(response1);
for (int i =0;i<jsonArr2.length();i++){
Assignedlist.add(jsonArr2.getString(i));
}
In Above It Returns a List which we are accepting as a List and then converting it to Json Array and then Json Array to List .
If Post Request passing Json Object as Parameter :
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:10102/NewsTickerServices/CreateJUser");
// value added
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,mapper.writeValueAsString(user));
if (response.getStatus() == 500) {
context.addMessage(null, new FacesMessage("User already exist "));
}
Seems like you have a single function that you need to call on two different parameters. This can be elegantly done using a combination of concurrent.futures
and map
with Python 3.2+
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def sleep_secs(seconds):
time.sleep(seconds)
print(f'{seconds} has been processed')
secs_list = [2,4, 6, 8, 10, 12]
Now, if your operation is IO bound, then you can use the ThreadPoolExecutor
as such:
with ThreadPoolExecutor() as executor:
results = executor.map(sleep_secs, secs_list)
Note how map
is used here to map
your function to the list of arguments.
Now, If your function is CPU bound, then you can use ProcessPoolExecutor
with ProcessPoolExecutor() as executor:
results = executor.map(sleep_secs, secs_list)
If you are not sure, you can simply try both and see which one gives you better results.
Finally, if you are looking to print out your results, you can simply do this:
with ThreadPoolExecutor() as executor:
results = executor.map(sleep_secs, secs_list)
for result in results:
print(result)
I recently ran into this issue for on old repo on my machine that had been pushed up using https. steps 5 and 6 solved my issue by re-setting the remote url for my repo from using the https url to the ssh url
checking the remote is using the https url
> git remote -v
origin https://github.com/ExampleUser/ExampleRepo.git (fetch)
origin https://github.com/ExampleUser/ExampleRepo.git (push)
then re-setting the origin to use the ssh url
> git remote set-url origin [email protected]:ExampleUser/ExampleRepo.git
verifying new remote
> git remote -v
origin [email protected]:ExampleUser/ExampleRepo.git (fetch)
origin [email protected]:ExampleUser/ExampleRepo.git (push)
could now successfully git push -u origin
i'm still not sure what setting i would have changed that might have caused the push to fail when the remote is https but this was the solution to my issue
There are several ways to perform HTTP GET
and POST
requests:
Available in: .NET Framework 4.5+
, .NET Standard 1.1+
, .NET Core 1.0+
.
It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.
using System.Net.Http;
It is recommended to instantiate one HttpClient
for your application's lifetime and share it unless you have a specific reason not to.
private static readonly HttpClient client = new HttpClient();
See HttpClientFactory
for a dependency injection solution.
POST
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
GET
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
POST
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
request.AddHeader("header", "value");
request.AddFile("file", path);
var response = client.Post(request);
var content = response.Content; // Raw content as string
var response2 = client.Post<Person>(request);
var name = response2.Data.Name;
It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.
using Flurl.Http;
POST
var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();
GET
var responseString = await "http://www.example.com/recepticle.aspx"
.GetStringAsync();
Available in: .NET Framework 1.1+
, .NET Standard 2.0+
, .NET Core 1.0+
. In .NET Core, it is mostly for compatibility -- it wraps HttpClient
, is less performant, and won't get new features.
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
POST
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
GET
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
This is a wrapper around HttpWebRequest
. Compare with HttpClient
.
Available in: .NET Framework 1.1+
, NET Standard 2.0+
, .NET Core 2.0+
using System.Net;
using System.Collections.Specialized;
POST
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}
GET
using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
Not sure if this is helpful but here's an example of Handlebars template with dynamic parameters passed to an inline RadioButtons partial and the client(browser) rendering the radio buttons in the container.
For my use it's rendered with Handlebars on the server and lets the client finish it up. With it a forms tool can provide inline data within Handlebars without helpers.
Note : This example requires jQuery
{{#*inline "RadioButtons"}}
{{name}} Buttons<hr>
<div id="key-{{{name}}}"></div>
<script>
{{{buttons}}}.map((o)=>{
$("#key-{{name}}").append($(''
+'<button class="checkbox">'
+'<input name="{{{name}}}" type="radio" value="'+o.value+'" />'+o.text
+'</button>'
));
});
// A little test script
$("#key-{{{name}}} .checkbox").on("click",function(){
alert($("input",this).val());
});
</script>
{{/inline}}
{{>RadioButtons name="Radio" buttons='[
{value:1,text:"One"},
{value:2,text:"Two"},
{value:3,text:"Three"}]'
}}
Type in console as root:
apt-get update && apt-get install php5-curl
or with sudo:
sudo apt-get update && sudo apt-get install php5-curl
Sorry I missread.
1st, check your DNS config and if you can ping any host at all,
ping google.com
ping zm.archive.ubuntu.com
If it does not work, check /etc/resolv.conf
or /etc/network/resolv.conf
, if not, change your apt-source to a different one.
/etc/apt/sources.list
Mirrors: http://www.debian.org/mirror/list
You should not use Ubuntu sources on Debian and vice versa.
Instead of finish()
call super.onBackPressed()
Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.
Covariance: accept subtypes
Contravariance: accept supertypes
Covariant types are read-only, while contravariant types are write-only.
Sorry guys for "resurrecting" the thread, but, I hope this will help someone:
In Python3 if you just want to "encapsulate" the class attributes, like in Java, you can just do the same thing like this:
class Simple:
def __init__(self, str):
print("inside the simple constructor")
self.__s = str
def show(self):
print(self.__s)
def showMsg(self, msg):
print(msg + ':', self.show())
To instantiate this do:
ss = Simple("lol")
ss.show()
Note that: print(ss.__s)
will throw an error.
In practice, Python3 will obfuscate the global attribute name. Turning this like a "private" attribute, like in Java. The attribute's name is still global, but in an inaccessible way, like a private attribute in other languages.
But don't be afraid of it. It doesn't matter. It does the job too. ;)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLbl: UILabel!
var containerView = UIView()
var loadingView = UIView()
var activityIndicator = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
let _ = Timer.scheduledTimer(withTimeInterval: 10, repeats: false) { (_) in
self.textLbl.text = "Stop ActivitiIndicator"
self.activityIndicator.stopAnimating()
self.containerView.removeFromSuperview()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func palyClicked(sender: AnyObject){
containerView.frame = self.view.frame
containerView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.3)
self.view.addSubview(containerView)
loadingView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
loadingView.center = self.view.center
loadingView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.5)
loadingView.clipsToBounds = true
loadingView.layer.cornerRadius = 10
containerView.addSubview(loadingView)
activityIndicator.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
activityIndicator.center = CGPoint(x:loadingView.frame.size.width / 2, y:loadingView.frame.size.height / 2);
activityIndicator.startAnimating()
loadingView.addSubview(activityIndicator)
}
}
I had this issue... It was the log that was huge. Logs are here :
/var/lib/docker/containers/<container id>/<container id>-json.log
You can manage this in the run command line or in the compose file. See there : Configure logging drivers
I personally added these 3 lines to my docker-compose.yml file :
my_container:
logging:
options:
max-size: 10m
The following example works on both ssl and non-ssl and is much faster as you use just one rule to manage http and https
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|offs()
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
[Tested]
This will redirect
http
to
https
to
I know this has an accepted answer, but in reading the replies on the answer, I see some things that I can clear up that might help other people having issues with events not triggering after a value change.
This will select the value in the drop-down:
$("#gate").val("gateway_2")
If this select element is using JQueryUI or other JQuery wrapper, use the refresh method of the wrapper to update the UI to show that the value has been selected. The below example is for JQueryUI, but you will have to look at the documentation for the wrapper you are using to determine the correct method for the refresh:
$("#gate").selectmenu("refresh");
If there is an event that needs to be triggered such as a change event, you will have to trigger that manually as changing the value does not fire the event. The event you need to fire depends on how the event was created:
If the event was created with JQuery i.e. $("#gate").on("change",function(){}) then trigger the event using the below method:
$("#gate").change();
If the event was created using a standard JavaScript event i.e. then trigger the event using the below method:
var JSElem = $("#gate")[0];
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
JSElem.dispatchEvent(evt);
} else {
JSElem.fireEvent("onchange");
}
An absolute xpath in HTML DOM starts with /html e.g.
/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]
and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.
.//*[@id='answers']/h2[1]/a[1]
You can use firepath (firebug) for generating both types of xpaths
It won't make any difference which xpath you use in selenium, the former may be faster than the later one (but it won't be observable)
Absolute xpaths are prone to more regression as slight change in DOM makes them invalid or refer to a wrong element
You can explore the json tree with gson.
Try something like this :
gson.toJsonTree(student).getAsJsonObject()
.get("country").getAsJsonObject().remove("name");
You can add some properties also :
gson.toJsonTree(student).getAsJsonObject().addProperty("isGoodStudent", false);
Tested with gson 2.2.4.
If the server resides on a remote machine, make sure the file in in the remote machine and not in your local machine.
If the file is in the same machine where the mysql server is, make sure the mysql user has permissions to read/write the file, or copy teh file into the mysql schema directory:
In my case in ubuntu it was: /var/lib/mysql/db_myschema/myfile.csv
Also, not relative to this problem, but if you have problems with the new lines, use sublimeTEXT to change the line endings to WINDOWS format, save the file and retry.
Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app
module, call mod_login.mod_login
app.py
from flask import Flask
import mod_login
# ...
do_stuff_with(mod_login.mod_login)
mod_login.py
from app import app
mod_login = something
To remove the variable from the current environment (not permanently):
set FOOBAR=
To permanently remove the variable from the user environment (which is the default place setx
puts it):
REG delete HKCU\Environment /F /V FOOBAR
If the variable is set in the system environment (e.g. if you originally set it with setx /M
), as an administrator run:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
Note: The REG
commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.
Just telling you about one other possibility: I like using friend definitions for that:
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
[...]
}
};
}
The function will be automatically targeted into the surrounding namespace Math
(even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>
.
This code achieves what you want --- also its weird and certainly buggy:
I observed that it works when:
a) you specify the index_col
rel. to the number of columns you really use -- so its three columns in this example, not four (you drop dummy
and start counting from then onwards)
b) same for parse_dates
c) not so for usecols
;) for obvious reasons
d) here I adapted the names
to mirror this behaviour
import pandas as pd
from StringIO import StringIO
csv = """dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5
"""
df = pd.read_csv(StringIO(csv),
index_col=[0,1],
usecols=[1,2,3],
parse_dates=[0],
header=0,
names=["date", "loc", "", "x"])
print df
which prints
x
date loc
2009-01-01 a 1
2009-01-02 a 3
2009-01-03 a 5
2009-01-01 b 1
2009-01-02 b 3
2009-01-03 b 5
In my case I needed to read from a downloaded script i.e. curl -Ss https://example.com/installer.sh | sh
The line read yesno < /dev/tty
made it
echo -n "These files will be uploaded. Is this ok? (y/n) "
read yesno < /dev/tty
if [ "x$yesno" = "xy" ];then
# Yes
else
# No
fi
Check: http://php.net/manual/en/function.mysql-affected-rows.php
Remove your script, and change the HTML:
<a id="closemodal" href="https://www.google.com" class="btn btn-primary close" data-dismiss="modal" target="_blank">Launch google.com</a>
EDIT: Please note that currently this will not work as this functionality does not yet exist in bootstrap. See issue here.
If you have a lot of binary data to read, you might want to consider the struct module. It is documented as converting "between C and Python types", but of course, bytes are bytes, and whether those were created as C types does not matter. For example, if your binary data contains two 2-byte integers and one 4-byte integer, you can read them as follows (example taken from struct
documentation):
>>> struct.unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
You might find this more convenient, faster, or both, than explicitly looping over the content of a file.
The observation that the event had to be initiated by the user helped me to figure out the first part of this, but even after that Chrome and Firefox still blocked the new window. The second part was adding target="_blank" to the link, which was mentioned in one comment.
In summary: you need to call window.open from an event initiated by the user, in this case clicking on a link, and that link needs to have target="_blank".
In the example below the link is using class="button-twitter".
$('.button-twitter').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var tweet_popup = window.open(href, 'tweet_popup', 'width=500,height=300');
});
Just a simple folder drill down.
sub sample()
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "C:\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
end sub
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub
Even if its not inline-block
based, this solution might worth consideration (allows nearly same formatting control from upper levels).
ul {
display: table;
}
ul li {
display: table-cell;
}
</li><li>
)Try with this code. I hope it's useful for you.
function sleep(seconds)
{
var e = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= e) {}
}
raise
causes an exception to be raised. Some other languages use the verb 'throw' instead.
It's intended to signal an error situation; it flags that the situation is exceptional to the normal flow.
Raised exceptions can be caught again by code 'upstream' (a surrounding block, or a function earlier on the stack) to handle it, using a try
, except
combination.
public function destroy($id) {
$news = News::findOrFail($id);
$image_path = app_path("images/news/".$news->photo);
if(file_exists($image_path)){
//File::delete($image_path);
File::delete( $image_path);
}
$news->delete();
return redirect('admin/dashboard')->with('message','??? ??????? ??? ??');
}
A complete solution for anyone that might need it, I've used this with good results so far
JS:
$(".btn-popover-container").each(function() {
var btn = $(this).children(".popover-btn");
var titleContainer = $(this).children(".btn-popover-title");
var contentContainer = $(this).children(".btn-popover-content");
var title = $(titleContainer).html();
var content = $(contentContainer).html();
$(btn).popover({
html: true,
title: title,
content: content,
placement: 'right'
});
});
HTML:
<div class="btn-popover-container">
<button type="button" class="btn btn-link popover-btn">Button Name</button>
<div class="btn-popover-title">
Popover Title
</div>
<div class="btn-popover-content">
<form>
Or Other content..
</form>
</div>
</div>
CSS:
.btn-popover-container {
display: inline-block;
}
.btn-popover-container .btn-popover-title, .btn-popover-container .btn-popover-content {
display: none;
}
Now this can be achieved with the JSONLib library:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
If (and only if) you use the overloaded toString(int indentationFactor)
method and not the standard toString()
method.
I have verified this on the following version of the API:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
From the documentation of String.split(String regex)
:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
So you will have to use the two argument version String.split(String regex, int limit)
with a negative value:
String[] split = data.split("\\|",-1);
Doc:
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
This will not leave out any empty elements, including the trailing ones.
Rather than grouping by visibility or by type of item (field, property, method, etc.), how about grouping by functionality?
Using the "point" leads to the creation of a folder named "point" (on Ubuntu 16).
tar -tf site1.bz2 -C /var/www/site1/ .
I dealt with this in more detail and prepared an example. Multi-line recording, plus an exception.
tar -tf site1.bz2\
-C /var/www/site1/ style.css\
-C /var/www/site1/ index.html\
-C /var/www/site1/ page2.html\
-C /var/www/site1/ page3.html\
--exclude=images/*.zip\
-C /var/www/site1/ images/
-C /var/www/site1/ subdir/
/
When the form is submitted:
document.activeElement
will give you the submit button that was clicked.
document.activeElement.getAttribute('value')
will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement
will be whichever form input
that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."
Run this command:
composer install --ignore-platform-reqs
or
composer update --ignore-platform-reqs
df.filter(df.location.contains('google.com'))
You can use plain SQL in
filter
df.filter("location like '%google.com%'")
or with DataFrame column methods
df.filter(df.location.like('%google.com%'))
I found this question because I wanted to do the same as the OP. I would like to add the following observation:
The iterative way (user225312, Sven Marnach):
list2 = [x for x in list1 if x]
Will return a list
object in python3
and python2
. Instead the filter way (lunaryorn, Imran) will differently behave over versions:
list2 = filter(None, list1)
It will return a filter
object in python3
and a list
in python2
(see this question found at the same time). This is a slight difference but it must be take in account when developing compatible scripts.
This does not make any assumption about performances of those solutions. Anyway the filter object can be reverted to a list using:
list3 = list(list2)
Just Change the Connection mysql string to 127.0.0.1 and it will work
Try this:
String numberStr = "3.5";
Float number = null;
try {
number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
System.out.println("numberStr is not a number");
}
You could use pandas
:
In [1]: import pandas as pd
In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]
In [3]: my_df = pd.DataFrame(a)
In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)
I'm not sure how they're functionally different. My current batch of OS X browsers don't show any difference.
I would assume they are all functionally the same due to legacy HTML attribute handling. Back in the day, any flag (Boolean) attribute need only be present, sans value, eg
<input readonly>
<option selected>
When XHTML came along, this syntax wasn't valid and values were required. Whilst the W3 specified using the attribute name as the value, I'm guessing most browser vendors decided to simply check for attribute existence.
Try the regex .{3,}
. This will match all characters except a new line.
Multi-line buttons like that are not really trivial to implement. This page has an interesting (though somewhat dated) discussion on the subject. Your best bet would probably be to either drop the multi-line requirement or to create a custom button using e.g. div
s and CSS, and adding some JavaScript to make it work as a button.
i had this problem and i solved it using javascript
location.reload(true);
you may also use
window.history.forward(1);
to stop the browser back button after user logs out of the application.
Others have already mentioned the dir() built-in which sounds like what you're looking for, but here's another good tip. Many libraries -- including most of the standard library -- are distributed in source form. Meaning you can pretty easily read the source code directly. The trick is in finding it; for example:
>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'
The *.pyc file is compiled, so remove the trailing 'c' and open up the uncompiled *.py file in your favorite editor or file viewer:
/usr/lib/python2.5/string.py
I've found this incredibly useful for discovering things like which exceptions are raised from a given API. This kind of detail is rarely well-documented in the Python world.
You could do a
mysqlimport --columns='head -n 1 $yourfile' --ignore-lines=1 dbname $yourfile`
That is, if your file is comma separated and is not semi-colon separated. Else you might need to sed
through it too.
It work for me
$request = new Request();
$request->headers->set('content-type', 'application/json');
$request->initialize(['yourParam' => 2]);
check output
$queryParams = $request->query();
dd($queryParams['yourParam']); // 2
To my knowledge these are the rules for calling subroutines and functions in VBScript:
Call
keyword enclose the arguments in parenthesisSince you probably wont be using the Call
keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.
Here are some examples:
WScript.Echo 1, "two", 3.3
- calling a subroutine
WScript.Echo(1, "two", 3.3)
- syntax error
Call WScript.Echo(1, "two", 3.3)
- keyword Call
requires parenthesis
MsgBox "Error"
- calling a function "like" a subroutine
result = MsgBox("Continue?", 4)
- calling a function where the return value is used
WScript.Echo (1 + 2)*3, ("two"), (((3.3)))
- calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)
WScript.Echo(1)
- apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1)
and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines
I'm not sure how to interpret your example, Randomize()
. Randomize
is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.
I'm quite sure that these syntactic rules applies across different versions of operating systems.
If you have no control over the page and wish to watch for some kind of change then the modern method is to use MutationObserver
An example of its use, watching for the src
attribute to change of an iframe
new MutationObserver(function(mutations) {_x000D_
mutations.some(function(mutation) {_x000D_
if (mutation.type === 'attributes' && mutation.attributeName === 'src') {_x000D_
console.log(mutation);_x000D_
console.log('Old src: ', mutation.oldValue);_x000D_
console.log('New src: ', mutation.target.src);_x000D_
return true;_x000D_
}_x000D_
_x000D_
return false;_x000D_
});_x000D_
}).observe(document.body, {_x000D_
attributes: true,_x000D_
attributeFilter: ['src'],_x000D_
attributeOldValue: true,_x000D_
characterData: false,_x000D_
characterDataOldValue: false,_x000D_
childList: false,_x000D_
subtree: true_x000D_
});_x000D_
_x000D_
setTimeout(function() {_x000D_
document.getElementsByTagName('iframe')[0].src = 'http://jsfiddle.net/';_x000D_
}, 3000);
_x000D_
<iframe src="http://www.google.com"></iframe>
_x000D_
Output after 3 seconds
MutationRecord {oldValue: "http://www.google.com", attributeNamespace: null, attributeName: "src", nextSibling: null, previousSibling: null…}
Old src: http://www.google.com
New src: http://jsfiddle.net/
On jsFiddle
Posted answer here as original question was closed as a duplicate of this one.
Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function??
I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.
class FigureOut:
first_name = None
last_name = None
def setName(self, name):
fullname = name.split()
self.first_name = fullname[0]
self.last_name = fullname[1]
self.special_name = fullname[2]
def getName(self):
return self.first_name, self.last_name, self.special_name
f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)
I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'
I hope my answer could help you. Happy coding.
In angularjs this should works:
event.preventDefault();
event.stopPropagation();
If you only want to clear the list box, you should use the Clear (winforms | wpf | asp.net) method:
ListBox2.Items.Clear()
If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).
To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
3. On Windows with Cygwin, you type "test1.sh" to run#!/bin/bash
echo '$0 = ' $0
echo '$1 = ' $1
filepath=$1
4. On a Unix, you also type "test1.sh" to run
Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.
Note: Using this method, you do not need to prepend your script file name with bash to run
You can use in the below format, Raw default value starting from 0, so
You can assign your own specific start value.
typedef enum : NSUInteger {
kCircle, // for your value; kCircle = 5, ...
kRectangle,
kOblateSpheroid
} ShapeType;
ShapeType circleShape = kCircle;
NSLog(@"%lu", (unsigned long) circleShape); // prints: 0
Here is a simple example:
EXEC sp_executesql @sql, N'@p1 INT, @p2 INT, @p3 INT', @p1, @p2, @p3;
Your call will be something like this
EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID
Step1: add permission on android manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step2: onCreate() method
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
} else {
readDataExternal();
}
Step3: override onRequestPermissionsResult method to get callback
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_MEDIA:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
readDataExternal();
}
break;
default:
break;
}
}
Note: readDataExternal() is method to get data from external storage.
Thanks.
If you have an AMD Ryzen processor in your computer you need the following setup requirements to be in place:
Note:There is Hyper-V features... You should enable Windows Hypervisor Platform not Hyper-V. Windows Hypervisor Platform is at the bottom
After conditions done avd x86 work without haxm install
answer for this question => Exception in thread "main" org.h2.jdbc.JdbcSQLException: Database may be already in use: "Locked by another process". Possible solutions: close all other connection(s); use the server mode [90020-161]
close all tab from your browser where open h2 database also Exit h2 engine from your pc
Starting Mongo 4.4
, we can achieve this join within an aggregation pipeline by coupling the new $unionWith
aggregation stage with $group
's new $accumulator
operator:
// > db.users.find()
// [{ user: 1, name: "x" }, { user: 2, name: "y" }]
// > db.books.find()
// [{ user: 1, book: "a" }, { user: 1, book: "b" }, { user: 2, book: "c" }]
// > db.movies.find()
// [{ user: 1, movie: "g" }, { user: 2, movie: "h" }, { user: 2, movie: "i" }]
db.users.aggregate([
{ $unionWith: "books" },
{ $unionWith: "movies" },
{ $group: {
_id: "$user",
user: {
$accumulator: {
accumulateArgs: ["$name", "$book", "$movie"],
init: function() { return { books: [], movies: [] } },
accumulate: function(user, name, book, movie) {
if (name) user.name = name;
if (book) user.books.push(book);
if (movie) user.movies.push(movie);
return user;
},
merge: function(userV1, userV2) {
if (userV2.name) userV1.name = userV2.name;
userV1.books.concat(userV2.books);
userV1.movies.concat(userV2.movies);
return userV1;
},
lang: "js"
}
}
}}
])
// { _id: 1, user: { books: ["a", "b"], movies: ["g"], name: "x" } }
// { _id: 2, user: { books: ["c"], movies: ["h", "i"], name: "y" } }
$unionWith
combines records from the given collection within documents already in the aggregation pipeline. After the 2 union stages, we thus have all users, books and movies records within the pipeline.
We then $group
records by $user
and accumulate items using the $accumulator
operator allowing custom accumulations of documents as they get grouped:
accumulateArgs
.init
defines the state that will be accumulated as we group elements.accumulate
function allows performing a custom action with a record being grouped in order to build the accumulated state. For instance, if the item being grouped has the book
field defined, then we update the books
part of the state.merge
is used to merge two internal states. It's only used for aggregations running on sharded clusters or when the operation exceeds memory limits.select * from sys.sysprocesses where dbid = DB_ID('Test')
(Replace 'Test' with the name of the database you are trying to drop) This will tell you which processes are using it.
If you still want to force drop then, the ultimate approach is:
USE master;
GO
ALTER DATABASE Test
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
DROP DATABASE Test;
Hope this helps !
when you render
a request tou coctext
some information:
for exampel:
return render(request, 'path to template',{'username' :username , 'email'.email})
you can acces to it on template like this :
for variabels :
{% if username %}{{ username }}{% endif %}
for array :
{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}
you can also name array objects in views.py
and ten use it like:
{% if username %}{{ username.first }}{% endif %}
if there is other problem i wish to help you
Or without (
and the need to escape it:
find . -not -name "*.exe" -not -name "*.dll"
and to also exclude the listing of directories
find . -not -name "*.exe" -not -name "*.dll" -not -type d
or in positive logic ;-)
find . -not -name "*.exe" -not -name "*.dll" -type f
add the following section and change :
Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all
change directory to your directory path like c:\wamp\www\projectfolder
make sure you make the same in httpd.conf for all directory like first directory:
Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all
second directory:
<Directory "c:/wamp/www/">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.0/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride all
#
# Controls who can get stuff from this server.
#
# onlineoffline tag - don't remove
Order Deny,Allow
Allow from all
</Directory>
<Directory "icons">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
As of Mongoose 3.8.x:
model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });
Where:
criteria
can be asc
, desc
, ascending
, descending
, 1
, or -1
Note: Use quotation marks or double quote
use "asc"
, "desc"
, "ascending"
, "descending"
, 1
, or -1
I simply do this in html:
<script>
$(document).load(function () {
d = new Date();
$('#<%= imgpreview.ClientID %>').attr('src','');
});
</script>
And reload the image in code behind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
image.Src = "/image.jpg"; //url caming from database
}
}
In case of CORS request all modern browsers respond with an OPTION verb, and then the actual request follows through. This is supposed to be used to prompt the user for confirmation in case of a CORS request. But in case of an API if you would want to skip this verification process add the following snippet to Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
Here we are just by passing the check by checking for OPTIONS verb.
This is slightly an edge case but I think it can add some value to the other answers.
If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.
For instance the following script:
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line
Will give you this figure, which is wrong:
While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);
# do potentially more stuff here
h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)
This is what you'll get:
here some itemdecoration for recyclerview
public class HeaderItemDecoration extends RecyclerView.ItemDecoration {
private View customView;
public HeaderItemDecoration(View view) {
this.customView = view;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
customView.layout(parent.getLeft(), 0, parent.getRight(), customView.getMeasuredHeight());
for (int i = 0; i < parent.getChildCount(); i++) {
View view = parent.getChildAt(i);
if (parent.getChildAdapterPosition(view) == 0) {
c.save();
final int height = customView.getMeasuredHeight();
final int top = view.getTop() - height;
c.translate(0, top);
customView.draw(c);
c.restore();
break;
}
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) == 0) {
customView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
outRect.set(0, customView.getMeasuredHeight(), 0, 0);
} else {
outRect.setEmpty();
}
}
}
Vectors and matrices can only be of a single type and cbind
and rbind
on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.
(Note that in your rbind
example, the promotion happens within the c
call:
> c(10, "[]", "[[1,2]]")
[1] "10" "[]" "[[1,2]]"
If you want a rectangular structure where the columns can be different types, you want a data.frame
. Any of the following should get you what you want:
> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
v1 v2 v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ v1: num 10 20
$ v2: Factor w/ 1 level "[]": 1 1
$ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using specifically the data.frame
version of cbind
)
> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c(10, 20) : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using cbind
, but making the first a data.frame
so that it combines as data.frames do):
> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c.10..20. : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL.
The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:
// anonymous delegate
var evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList();
// lambda expression
var evens = Enumerable
.Range(1, 100)
.Where(x => (x % 2) == 0)
.ToList();
Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects.
Expression trees are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an Expression<T>
parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:
void Example(Predicate<int> aDelegate);
called like:
Example(x => x > 5);
becomes:
void Example(Expression<Predicate<int>> expressionTree);
The latter will get passed a representation of the abstract syntax tree that describes the expression x > 5
. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.
Just as you would with a CheckBox
RadioButton rb;
rb = (RadioButton) findViewById(R.id.rb);
rb.isChecked();
Rails' ActiveSupport adds underscore to the String using the following:
class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
Then you can do fun stuff:
"CamelCase".underscore
=> "camel_case"
I worked around this exact error by not adding the ListBox to a parent Page/Control Controls collection. Because I really didn't need any server-side functionality out of it. I just wanted to use it to output the HTML for a custom server control, which I did in the OnRender event handler myself. I hoped that using the control would save me from writing to the response my own html.
This solution probably won't work for most, but it keeps ASP.NET from performing the ValidateEvent against the control, because the control doesn't retain in memory between postbacks.
Also, my error was specifically caused by the selected list item being an item that wasn't in the listbox the previous postback. Incase that helps anyone.
For those of us trying to figure out how to hash our own classes whilst still using the standard template, there is a simple solution:
In your class you need to define an equality operator overload ==
. If you don't know how to do this, GeeksforGeeks has a great tutorial https://www.geeksforgeeks.org/operator-overloading-c/
Under the standard namespace, declare a template struct called hash with your classname as the type (see below). I found a great blogpost that also shows an example of calculating hashes using XOR and bitshifting, but that's outside the scope of this question, but it also includes detailed instructions on how to accomplish using hash functions as well https://prateekvjoshi.com/2014/06/05/using-hash-function-in-c-for-user-defined-classes/
namespace std {
template<>
struct hash<my_type> {
size_t operator()(const my_type& k) {
// Do your hash function here
...
}
};
}
std::map
or std::unordered_map
just like you would normally do and use my_type
as the key, the standard library will automatically use the hash function you defined before (in step 2) to hash your keys.#include <unordered_map>
int main() {
std::unordered_map<my_type, other_type> my_map;
}
@curt is correct, but I've noticed that sometimes even this fails with NULL disallowed errors, and it seems to be intermittent.
I avoided the error at all times, by also setting the Indenty Seed to 1 and IDENTITY(1, 1) NOT FOR REPLICATION
.
An example based on Chuck's answer:
myIntToStr :: Int -> String
myIntToStr x
| x < 3 = show x ++ " is less than three"
| otherwise = "normal"
Note that without the show
the third line will not compile.
You could have a div for the top with one background and another for the main page, and seperate the page content between them or put the content in a floating div on another z-level. The way you are doing it may work but I doubt it will work across every browser you encounter.
Add this line to pg_hba.conf of postgres folder
host all all all trust
"trust" allows all users to connect without any password.
I found I needed more than just the Visual C++ Redistributable 2015.
I also needed what's at this page. It's confusing because the titles make it ambiguous as to whether you're downloading the (very heavy) Visual Studio or just Visual C++. In this case it only upgrades Visual C++, and MySQL Workbench launched after this install.
NUMERIC(3,2)
means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.
Try NUMERIC(5,2)
- three before, two after the decimal point.
This link should get you started. Long story short, a div that has been styled to look like a scrollbar is used to catch click-and-drag events. Wired up to these events are methods that scroll the contents of another div which is set to an arbitrary height and typically has a css rule of overflow:scroll (there are variants on the css rules but you get the idea).
I'm all about the learning experience -- but after you've learned how it works, I recommend using a library (of which there are many) to do it. It's one of those "don't reinvent" things...
When i try create another package
under the Java folder
this error will happen
But When i moved this special package under the main package
of my project , everything will be ok .
I'm testing on real android device .(Sumsung J2)
I found this question by searching Google for "mysql workbench export database sql file". The answers here did not help me, but I eventually did find the answer, so I am posting it here for future generations to find:
Answer
In MySQLWorkbench 6.0, do the following:
Here is a screenshot for reference:
A complete method tested on iOS 7 and iOS 8.
@interface UIViewController (MBOverCurrentContextModalPresenting)
/// @warning Some method of viewControllerToPresent will called twice before iOS 8, e.g. viewWillAppear:.
- (void)MBOverCurrentContextPresentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion;
@end
@implementation UIViewController (MBOverCurrentContextModalPresenting)
- (void)MBOverCurrentContextPresentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
UIViewController *presentingVC = self;
// iOS 8 before
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
UIViewController *root = presentingVC;
while (root.parentViewController) {
root = root.parentViewController;
}
[presentingVC presentViewController:viewControllerToPresent animated:YES completion:^{
[viewControllerToPresent dismissViewControllerAnimated:NO completion:^{
UIModalPresentationStyle orginalStyle = root.modalPresentationStyle;
if (orginalStyle != UIModalPresentationCurrentContext) {
root.modalPresentationStyle = UIModalPresentationCurrentContext;
}
[presentingVC presentViewController:viewControllerToPresent animated:NO completion:completion];
if (orginalStyle != UIModalPresentationCurrentContext) {
root.modalPresentationStyle = orginalStyle;
}
}];
}];
return;
}
UIModalPresentationStyle orginalStyle = viewControllerToPresent.modalPresentationStyle;
if (orginalStyle != UIModalPresentationOverCurrentContext) {
viewControllerToPresent.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}
[presentingVC presentViewController:viewControllerToPresent animated:YES completion:completion];
if (orginalStyle != UIModalPresentationOverCurrentContext) {
viewControllerToPresent.modalPresentationStyle = orginalStyle;
}
}
@end
Try kiwi, a light-weight JavaScript module for string interpolation.
You can do
Kiwi.compose("I'm % years old!", [age]);
or
Kiwi.compose("I'm %{age} years old!", {"age" : age});
Do you have Bitnami installed? If so it is most likely one of those installations check by opening command prompt as admin or terminal in linux, enter this...
netstat -b
This will give an application name to those processes and ports in use. Look for :80 or :443
SELECT NEXT_DAY (TO_DATE ('01/01/'||SUBSTR('201118',1,4),'MM/DD/YYYY')+(TO_NUMBER(SUBSTR('201118',5,2))*7)-3,'SUNDAY')-7 first_day_wk,
NEXT_DAY (TO_DATE ('01/01/'||SUBSTR('201118',1,4),'MM/DD/YYYY')+(TO_NUMBER(SUBSTR('201118',5,2))*7)-3,'SATURDAY') last_day_wk FROM dual
Original Answer
Windows Grep does this really well.
Edit: Windows Grep is no longer being maintained or made available by the developer. An alternate download link is here: Windows Grep - alternate
Current Answer
Visual Studio Code has excellent search and replace capabilities across files. It is extremely fast, supports regex and live preview before replacement.
If you're looking to paginate results, use the integrated paginator, it works great!
$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages
let's take an example first
list1=[1,2,3,4]
list2=list1 (that means they points to same object)
if we do
list1=list1+[5] it will create a new object of list
print(list1) output [1,2,3,4,5]
print(list2) output [1,2,3,4]
but if we append then
list1.append(5) no new object of list created
print(list1) output [1,2,3,4,5]
print(list2) output [1,2,3,4,5]
extend(list) also do the same work as append it just append a list instead of a
single variable
Sometimes this error happens because of unexpected CR characters in file, usually because the file was generated on a Windows system which uses CR line endings. You can fix this by running os2unix
or tr
, for example:
tr -d '\015' < yourscript.sh > newscript.sh
This removes any CR characters from the file.
You can also pass an array as the second argument after the view template name, instead of stringing together a bunch of ->with()
methods.
return View::make('blog', array('posts' => $posts));
Or, if you're using PHP 5.4 or better you can use the much nicer "short" array syntax:
return View::make('blog', ['posts' => $posts]);
This is useful if you want to compute the array elsewhere. For instance if you have a bunch of variables that every controller needs to pass to the view, and you want to combine this with an array of variables that is unique to each particular controller (using array_merge
, for instance), you might compute $variables
(which contains an array!):
return View::make('blog', $variables);
(I did this off the top of my head: let me know if a syntax error slipped in...)
Since 1.25.4, docker-compose supports the option --env-file
that enables you to specify a file containing variables.
Yours should look like this:
hostname=my-host-name
And the command:
docker-compose --env-file /path/to/my-env-file config
As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.
To answer your specific questions:
Indeed, there is type conversion to int. Also you can force type to char by using %hhx specifier.
printf("%hhX", a);
In most cases you will want to set the minimum length as well to fill the second character with zeroes:
printf("%02hhX", a);
ISO/IEC 9899:201x says:
7 The length modifiers and their meanings are: hh Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following
With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.
var json = Json.Encode(new {
orientation = Cache["orientation"],
alerted = Cache["alerted"] as bool?,
since = Cache["since"] as DateTime?
});
Response.Write(json);
You can revert uncommitted changes only to particular file or directory:
git checkout [some_dir|file.txt]
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
return "This is a String";
}
You can use the 'describe pod' syntax
For OpenShift use:
oc describe pod <pod-id>
For vanilla Kubernetes:
kubectl describe pod <pod-id>
Examine the events of the output. In my case it shows Back-off pulling image coredns/coredns:latest
In this case the image coredns/coredns:latest can not be pulled from the Internet.
Events:
FirstSeen LastSeen Count From SubObjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
5m 5m 1 {default-scheduler } Normal Scheduled Successfully assigned coredns-4224169331-9nhxj to 192.168.122.190
5m 1m 4 {kubelet 192.168.122.190} spec.containers{coredns} Normal Pulling pulling image "coredns/coredns:latest"
4m 26s 4 {kubelet 192.168.122.190} spec.containers{coredns} Warning Failed Failed to pull image "coredns/coredns:latest": Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your internet connection or if you are behind a proxy.
4m 26s 4 {kubelet 192.168.122.190} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ErrImagePull: "Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your Internet connection or if you are behind a proxy."
4m 2s 7 {kubelet 192.168.122.190} spec.containers{coredns} Normal BackOff Back-off pulling image "coredns/coredns:latest"
4m 2s 7 {kubelet 192.168.122.190} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ImagePullBackOff: "Back-off pulling image \"coredns/coredns:latest\""
Additional debuging steps
use further as
rs.getString(1);
rs.getInt(2);
1, 2 is the column number of table and set int or string as per data-type of coloumn
Other solutions didn't work in one of my projects and I've ending up checking overflow css property
function haveScrollbar() {
var style = window.getComputedStyle(document.body);
return style["overflow-y"] != "hidden";
}
but it will only work if scrollbar appear disappear by changing the prop it will not work if the content is equal or smaller than the window.
Your approach is OK
Maybe slightly clearer (to me anyway!)
UPDATE
T1
SET
[Description] = t2.[Description]
FROM
Table1 T1
JOIN
[Table2] t2 ON t2.[ID] = t1.DescriptionID
Both this and your query should run the same performance wise because it is the same query, just laid out differently.
Note to Sinan and brian: perlfaq3 is still wrong.
In my case I need both XAMPP for Apache development & IIS Express for .Net 2013 development; so I do the following:
In Command Prompt typed services.msc, this loads "Windows Services" where I located "World Wide Web Publishing Service" and stop it. World Wide Web Publishing Service STOP
The I start XAMPP Control Panel click on "Config", then choose "Apache httpd.conf". Search for "80" then change that to "8080" in both "Listen 80" and "ServerName localhost:80". Save the file from "Save As" & choose "All files" to not save it as text from "Save As Type" & the "Encoding" should be "UTF-8". Apache httpd.conf
Quit XAMPP Control Panel, then start it again and from "Action" start Apache & MySQL. Now you will see the port changed. As you know now you have to get to your Apache server by using "localhost:8080" instead of "localhost". Also you have both Apache & IIS Express running in the same Windows 10 PC.
I read a post some where were the writer suggested to use port "9080" but it did not work for me.
It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.
You can do it by subfolders (example /css/v1/style.css)
or by filename (example: css/style_v1.css)
or even by setting different folders for your website, example:
www.mywebsite.com/site1
www.mywebsite.com/site2
www.mywebsite.com/site3
And use a .htaccess or even change httpd.conf to redirect to your current application.
If's about one image or page:
<?$time = date("H:i:s");?>
<img src="myfile.jpg?time=<?$time;?>">
You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.
I am using DBLINK to connect internal database for cross database queries.
Reference taken from this article.
Install DbLink extension.
CREATE EXTENSION dblink;
Verify DbLink:
SELECT pg_namespace.nspname, pg_proc.proname
FROM pg_proc, pg_namespace
WHERE pg_proc.pronamespace=pg_namespace.oid
AND pg_proc.proname LIKE '%dblink%';
Test connection of database:
SELECT dblink_connect('host=localhost user=postgres password=enjoy dbname=postgres');
Look at http.request
var options = {
host: url,
port: 80,
path: '/resource?id=foo&bar=baz',
method: 'POST'
};
http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
}).end();
git config --list
git config -l
will display your username and email together, along with other info
According to Android Sqlite get last insert row id there is another query:
SELECT rowid from your_table_name order by ROWID DESC limit 1
Interestingly array is randomly accessible by the index. And removing randomly an element may impact the indexes of other elements as well.
int remove_element(int*from, int total, int index) {
if((total - index - 1) > 0) {
memmove(from+i, from+i+1, sizeof(int)*(total-index-1));
}
return total-1; // return the new array size
}
Note that memcpy
will not work in this case because of the overlapping memory.
One of the efficient way (better than memory move) to remove one random element is swapping with the last element.
int remove_element(int*from, int total, int index) {
if(index != (total-1))
from[index] = from[total-1];
return total; // **DO NOT DECREASE** the total here
}
But the order is changed after the removal.
Again if the removal is done in loop operation then the reordering may impact processing. Memory move is one expensive alternative to keep the order while removing an array element. Another of the way to keep the order while in a loop is to defer the removal. It can be done by validity array of the same size.
int remove_element(int*from, int total, int*is_valid, int index) {
is_valid[index] = 0;
return total-1; // return the number of elements
}
It will create a sparse array. Finally, the sparse array can be made compact(that contains no two valid elements that contain invalid element between them) by doing some reordering.
int sparse_to_compact(int*arr, int total, int*is_valid) {
int i = 0;
int last = total - 1;
// trim the last invalid elements
for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements from last
// now we keep swapping the invalid with last valid element
for(i=0; i < last; i++) {
if(is_valid[i])
continue;
arr[i] = arr[last]; // swap invalid with the last valid
last--;
for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements
}
return last+1; // return the compact length of the array
}
This works for me. Hope it will work for you too.
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);
I have edited the html page which you have provided. The updated page is as below
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Test() {
alert("Hello Test!!!!");
$('#ButtonRow').css("display", "block");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
BorderStyle="Solid">
<asp:ListItem>Merchant</asp:ListItem>
<asp:ListItem>Store</asp:ListItem>
<asp:ListItem>Terminal</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr id="ButtonRow" style="display: none">
<td>
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$("#<%=SearchCategory.ClientID%> input").change(function () {
alert("hi");
$("#ButtonRow").show();
});
</script>
There is a similar problem.it is a tomcat digital signature.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc apache-tomcat-9.0.16-windows-
x64.zip
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key
but then I use the RSA key it provided to receive the public key to verify.
$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg: imported: 1
Then successfully.
$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc
gpg: assuming signed data in 'apache-tomcat-9.0.16-windows-x64.zip'
gpg: Signature made 2019?02? 5? 0:32:50
gpg: using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987 5A51 10C0 1C5A 2F60 59E7
You could use the following query:
SELECT table1.id
FROM table1
LEFT JOIN table2
ON table1.id IN (table2.user_one, table2.user_two)
WHERE table2.user_one IS NULL;
Although, depending on your indexes on table2
you may find that two joins performs better:
SELECT table1.id
FROM table1
LEFT JOIN table2 AS t1
ON table1.id = t1.user_one
LEFT JOIN table2 AS t2
ON table1.id = t2.user_two
WHERE t1.user_one IS NULL
AND t2.user_two IS NULL;
No need to use grep. ps
in Android can filter by COMM
value (last 15 characters of the package name in case of java app)
Let's say we want to check if com.android.phone
is running:
adb shell ps m.android.phone
USER PID PPID VSIZE RSS WCHAN PC NAME
radio 1389 277 515960 33964 ffffffff 4024c270 S com.android.phone
Filtering by COMM
value option has been removed from ps
in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof
command:
adb shell pidof com.android.phone
It returns the PID if such process was found or an empty string otherwise.
Try escaping the slash: someString.replace(/\//g, "-");
By the way - /
is a (forward-)slash; \
is a backslash.
One important thing I missed from the tutorials for a while (stolen from http://www.tramontana.co.hu/wix/lesson4.php) which resulted in the "Another version of this product is already installed" errors:
*Small updates mean small changes to one or a few files where the change doesn't warrant changing the product version (major.minor.build). You don't have to change the Product GUID, either. Note that you always have to change the Package GUID when you create a new .msi file that is different from the previous ones in any respect. The Installer keeps track of your installed programs and finds them when the user wants to change or remove the installation using these GUIDs. Using the same GUID for different packages will confuse the Installer.
Minor upgrades denote changes where the product version will already change. Modify the Version attribute of the Product tag. The product will remain the same, so you don't need to change the Product GUID but, of course, get a new Package GUID.
Major upgrades denote significant changes like going from one full version to another. Change everything: Version attribute, Product and Package GUIDs.
This will get the interface associated to the default route
NET_IF=`netstat -rn | awk '/^0.0.0.0/ {thif=substr($0,74,10); print thif;} /^default.*UG/ {thif=substr($0,65,10); print thif;}'`
Using the interface discovered above, get the ip address.
NET_IP=`ifconfig ${NET_IF} | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'`
uname -a
Darwin laptop 14.4.0 Darwin Kernel Version 14.4.0: Thu May 28 11:35:04 PDT 2015; root:xnu-2782.30.5~1/RELEASE_X86_64 x86_64
echo $NET_IF
en5
echo $NET_IP
192.168.0.130
uname -a
Linux dev-cil.medfx.local 2.6.18-164.el5xen 1 SMP Thu Sep 3 04:03:03 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux
echo $NET_IF
eth0
echo $NET_IP
192.168.46.10
Cleaner and an all in one solution :D
//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);