Can be done using python XOR operator.
set(temp1) ^ set(temp2)
The answer above was 90% of what I needed, but returned a Uri instead of a regular path for me.
As explained in the MSDN forums post, How to convert URI path to normal filepath?, I used the following:
// Get normal filepath of this assembly's permanent directory
var path = new Uri(
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
).LocalPath;
This is a variation of n3rds solution above. No sorting by using ORDER BY is needed, as MIN() is used.
Remember that CustomerID (or whatever other numerical column you use for progress) must have a unique constraint. Furthermore, to make it as fast as possible CustomerID must be indexed on.
-- Declare & init
DECLARE @CustomerID INT = (SELECT MIN(CustomerID) FROM Sales.Customer); -- First ID
DECLARE @Data1 VARCHAR(200);
DECLARE @Data2 VARCHAR(200);
-- Iterate over all customers
WHILE @CustomerID IS NOT NULL
BEGIN
-- Get data based on ID
SELECT @Data1 = Data1, @Data2 = Data2
FROM Sales.Customer
WHERE [ID] = @CustomerID ;
-- call your sproc
EXEC dbo.YOURSPROC @Data1, @Data2
-- Get next customerId
SELECT @CustomerID = MIN(CustomerID)
FROM Sales.Customer
WHERE CustomerID > @CustomerId
END
I use this approach on some varchars I need to look over, by putting them in a temporary table first, to give them an ID.
Try this one:
var comment = document.querySelector("button");
function showComment() {
var place = document.querySelector('#textfield');
var commentBox = document.createElement('textarea');
place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);
Use querySelector
instead of className
Write bytes and Create the file if not exists:
f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()
wb
means open the file in write binary
mode.
If you are using a pycharm IDE for development and you already have added Git with it. you can directly delete remote branch from pycharm. From toolbar VCS-->Git-->Branches-->Select branch-->and Delete. It will delete it from remote git server.
Essentially, use an <a>
element with an href
attr pointing to the phone number prefixed by tel:
. Note that pluses can be used to specify country code, and hyphens can be included simply for human eyes.
MDN Web Docs
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Creating_a_phone_link
The HTML
<a>
element (or anchor element), along with its href attribute, creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.[…]
Offering phone links is helpful for users viewing web documents and laptops connected to phones.
<a href="tel:+491570156">+49 157 0156</a>
IETF Documents
https://tools.ietf.org/html/rfc3966
The
tel
URI for Telephone NumbersThe "tel" URI has the following syntax:
telephone-uri
="tel:"
telephone-subscriber[…]
Examples
tel:+1-201-555-0123
: This URI points to a phone number in the United States. The hyphens are included to make the number more human readable; they separate country, area code and subscriber number.
tel:7042;phone-context=example.com
: The URI describes a local phone number valid within the context "example.com".
tel:863-1234;phone-context=+1-914-555
: The URI describes a local phone number that is valid within a particular phone prefix.
CREATE PROCEDURE [dbo].[describe]
(
@SearchStr nvarchar(max)
)
AS
BEGIN
SELECT
CONCAT([COLUMN_NAME],' ',[DATA_TYPE],' ',[CHARACTER_MAXIMUM_LENGTH],' ',
(SELECT CASE [IS_NULLABLE] WHEN 'NO' THEN 'NOT NULL' ELSE 'NULL' END),
(SELECT CASE WHEN [COLUMN_DEFAULT] IS NULL THEN '' ELSE CONCAT(' DEFAULT ',[COLUMN_DEFAULT]) END)
) AS DESCRIPTION
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE @SearchStr
END
From here:
The function
ord()
gets the int value of the char. And in case you want to convert back after playing with the number, functionchr()
does the trick.
>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>
In Python 2, there was also the unichr
function, returning the Unicode character whose ordinal is the unichr
argument:
>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'
In Python 3 you can use chr
instead of unichr
.
I ran into the same problem, and I solved it by running the following commands which is given here
pod repo remove master
pod setup
pod install
I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);
plt.show()
This is the output:
Follow to below instructions:
1:) Open your AndroidManifest.xml
file.
2:) Go to the activity code which you want to make your main activity like below.
such as i want to make SplashScreen as main activity
<activity
android:name=".SplashScreen"
android:screenOrientation="sensorPortrait"
android:label="City Retails">
</activity>
3:) Now copy the below code in between activity tags same as:
<activity
android:name=".SplashScreen"
android:screenOrientation="sensorPortrait"
android:label="City Retails">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
and also check that newly added lines are not attached with other activity tags.
The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function.
Use
Z=XY[0]+XY[1]
Instead of
Z=XY(i,0)+XY(i,1)
The updated or deleted values are stored in DELETED. we can get it by the below method in trigger
Full example,
CREATE TRIGGER PRODUCT_UPDATE ON PRODUCTS
FOR UPDATE
AS
BEGIN
DECLARE @PRODUCT_NAME_OLD VARCHAR(100)
DECLARE @PRODUCT_NAME_NEW VARCHAR(100)
SELECT @PRODUCT_NAME_OLD = product_name from DELETED
SELECT @PRODUCT_NAME_NEW = product_name from INSERTED
END
Actually the "Remote" option in Configuration Menu for Plug-In works by me (Win7 64, ie8 with all updates), however:
Also the previous comment about browsing-history->view objects was also useful if plug-in was installed right now.
Regards!
You can use Microsoft's WFetch tool also. This is a good tool for all HTTP operations.
UPDATED FOR XCODE 9 (Via Interface Builder)
There's an easier way from the Interface Builder.
Select the UIButton and select this option in the View Utilities > Semantic:
OPTIONAL - 2nd step:
If you want to adjust the spacing between the image and the title you can change the Image Inset here:
Hope that helps!
Another example, in C
printf (" %.20f \n", 3.6);
incredibly gives
3.60000000000000008882
That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:
setx ENV_VAR_NAME "DESIRED_PATH" /m
This will change it permanently and yes you can overwrite it by another batch script.
this.WindowState = FormWindowState.Minimized;
This will also work
>>> u=1./5
>>> print u
0.2
This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).
The markup
<table class="table">
<thead>
<tr>
<th>
<input type="checkbox"
ng-click="selectAll($event)"
ng-checked="isSelectedAll()">
</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
<td>
<input type="checkbox" name="selected"
ng-checked="isSelected(e.id)"
ng-click="updateSelection($event, e.id)">
</td>
<td>{{e.title}}</td>
</tr>
</tbody>
</table>
And in the controller
var updateSelected = function(action, id) {
if (action === 'add' && $scope.selected.indexOf(id) === -1) {
$scope.selected.push(id);
}
if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
$scope.selected.splice($scope.selected.indexOf(id), 1);
}
};
$scope.updateSelection = function($event, id) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
updateSelected(action, id);
};
$scope.selectAll = function($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
for ( var i = 0; i < $scope.entities.length; i++) {
var entity = $scope.entities[i];
updateSelected(action, entity.id);
}
};
$scope.getSelectedClass = function(entity) {
return $scope.isSelected(entity.id) ? 'selected' : '';
};
$scope.isSelected = function(id) {
return $scope.selected.indexOf(id) >= 0;
};
//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
return $scope.selected.length === $scope.entities.length;
};
EDIT: getSelectedClass()
expects the entire entity but it was being called with the id of the entity only, which is now corrected
This is worked on Marshmallow
private final String TAG = "OnOffScreen";
private PowerManager _powerManager;
private PowerManager.WakeLock _screenOffWakeLock;
public void turnOnScreen() {
if (_screenOffWakeLock != null) {
_screenOffWakeLock.release();
}
}
public void turnOffScreen() {
try {
_powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
if (_powerManager != null) {
_screenOffWakeLock = _powerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
if (_screenOffWakeLock != null) {
_screenOffWakeLock.acquire();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between()
:
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)
plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()
See also the matplotlib examples.
There are a several things you need to address to get it working
@ouput
its @code
AddWithValue
since its not supposed to have a value just you Add
.ExecuteNonQuery
if you're not returning rows Try
SqlParameter output = new SqlParameter("@code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
MessageBox.Show(output.Value.ToString());
In case that you still can't use "import" here is how I handled it: Just translate it to a node friendly require. Example:
import { parse } from 'node-html-parser';
Is the same as:
const parse = require('node-html-parser').parse;
VS2013 on 64-bit Windows 7 requires these settings: Tools | Options | Source Control | Jazz Source Control
CHECK THE CHECKBOX Use an external compare tool ... (easy to miss this)
2-Way Compare Location of Executable: C:\Program Files (x86)\Beyond Compare 3\BCompare.exe
3-Way Conflict Compare Location of Executable: C:\Program Files (x86)\Beyond Compare 3\BCompare.exe
When you upload a file using FileField
, the file will have a URL that you can use to point to the file and use HTML download
attribute to download that file you can simply do this.
models.py
The model.py looks like this
class CsvFile(models.Model):
csv_file = models.FileField(upload_to='documents')
views.py
#csv upload
class CsvUploadView(generic.CreateView):
model = CsvFile
fields = ['csv_file']
template_name = 'upload.html'
#csv download
class CsvDownloadView(generic.ListView):
model = CsvFile
fields = ['csv_file']
template_name = 'download.html'
Then in your templates.
#Upload template
upload.html
<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>
#download template
download.html
{% for document in object_list %}
<a href="{{ document.csv_file.url }}" download class="btn btn-dark float-right">Download</a>
{% endfor %}
I did not use forms, just rendered model but either way, FileField is there and it will work the same.
public class ListElementAdapter extends BaseAdapter{
String[] data;
Context context;
LayoutInflater layoutInflater;
public ListElementAdapter(String[] data, Context context) {
super();
this.data = data;
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return data.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView= layoutInflater.inflate(R.layout.item, null);
TextView txt=(TextView)convertView.findViewById(R.id.text);
txt.setText(data[position]);
return convertView;
}
}
Just call ListElementAdapter in your Main Activity and set Adapter to ListView.
I wanted to do something similar, except setting the number to NaN rather than removing it from the data, since if you remove it you change the length which can mess up plotting (i.e. if you're only removing outliers from one column in a table, but you need it to remain the same as the other columns so you can plot them against each other).
To do so I used numpy's masking functions:
def reject_outliers(data, m=2):
stdev = np.std(data)
mean = np.mean(data)
maskMin = mean - stdev * m
maskMax = mean + stdev * m
mask = np.ma.masked_outside(data, maskMin, maskMax)
print('Masking values outside of {} and {}'.format(maskMin, maskMax))
return mask
If you're looking for a recursive directory listing solutions. Use below code I hope it should help you.
<?php
/**
* Function for recursive directory file list search as an array.
*
* @param mixed $dir Main Directory Path.
*
* @return array
*/
function listFolderFiles($dir)
{
$fileInfo = scandir($dir);
$allFileLists = [];
foreach ($fileInfo as $folder) {
if ($folder !== '.' && $folder !== '..') {
if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
$allFileLists[$folder . '/'] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
} else {
$allFileLists[$folder] = $folder;
}
}
}
return $allFileLists;
}//end listFolderFiles()
$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'
?>
Fetch both the key and the value from the dictionary in the loop:
{% for key, value in mydict.items %}
{{ value }}
{% endfor %}
I find this easier to read and it avoids the need for special coding. I usually need the key and the value inside the loop anyway.
The other main difference is that table variables don't have column statistics, where as temp tables do. This means that the query optimiser doesn't know how many rows are in the table variable (it guesses 1), which can lead to highly non-optimal plans been generated if the table variable actually has a large number of rows.
Two issues jump out:
Your getData
never returns anything, so its promise (async
functions always return a promise) will resolve with undefined
when it resolves
The error message clearly shows you're trying to directly render the promise getData
returns, rather than waiting for it to resolve and then rendering the resolution
Addressing #1: getData
should return the result of calling json
:
async getData(){
const res = await axios('/data');
return await res.json();
}
Addressig #2: We'd have to see more of your code, but fundamentally, you can't do
<SomeElement>{getData()}</SomeElement>
...because that doesn't wait for the resolution. You'd need instead to use getData
to set state:
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
...and use that state when rendering:
<SomeElement>{this.state.data}</SomeElement>
Update: Now that you've shown us your code, you'd need to do something like this:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
Futher update: You've indicated a preference for using await
in componentDidMount
rather than then
and catch
. You'd do that by nesting an async
IIFE function within it and ensuring that function can't throw. (componentDidMount
itself can't be async
, nothing will consume that promise.) E.g.:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.
First specification of url-pattern
a web.xml
file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern>
as follows:
http://server.com/server/status/synopsis = Matches
http://server.com/server/status/complete?date=today = Matches
http://server.com/server/status = Matches
http://server.com/server/server1/status = Does not match
Second specification of url-pattern
A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern>
as follows:
http://server.com/server/US/Oregon/Portland.map = Matches
http://server.com/server/US/server/Seattle.map = Matches
http://server.com/server/Paris.France.map = Matches
http://server.com/server/US/Oregon/Portland.MAP = Does not match, the extension is uppercase
http://example.com/examples/interface/description/mail.mapi =Does not match, the extension is mapi rather than map`
Third specification of url-mapping
,A mapping that contains the pattern <url-pattern>/</url-pattern>
matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.
The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.
The servlet-mapping element below maps the server
servlet instance to the default mapping.
<servlet-mapping>
<servlet-name>server</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
For the context that contains this element, any request that is not handled by another mapping is forwarded to the server
servlet.
And Most importantly we should Know about Rule for URL path mapping
Reference URL Pattern
package anywheresoftware.b4a.student;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;
public class ShakeEventListener implements SensorEventListener {
/*
* The gForce that is necessary to register as shake.
* Must be greater than 1G (one earth gravity unit).
* You can install "G-Force", by Blake La Pierre
* from the Google Play Store and run it to see how
* many G's it takes to register a shake
*/
private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F;
private static int SHAKE_SLOP_TIME_MS = 500;
private static final int SHAKE_COUNT_RESET_TIME_MS = 1000;
private OnShakeListener mListener;
private long mShakeTimestamp;
private int mShakeCount;
public void setOnShakeListener(OnShakeListener listener) {
this.mListener = listener;
}
public interface OnShakeListener {
public void onShake(int count);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// ignore
}
@Override
public void onSensorChanged(SensorEvent event) {
if (mListener != null) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
float gX = x / SensorManager.GRAVITY_EARTH;
float gY = y / SensorManager.GRAVITY_EARTH;
float gZ = z / SensorManager.GRAVITY_EARTH;
// gForce will be close to 1 when there is no movement.
float gForce = FloatMath.sqrt(gX * gX + gY * gY + gZ * gZ);
if (gForce > SHAKE_THRESHOLD_GRAVITY) {
final long now = System.currentTimeMillis();
// ignore shake events too close to each other (500ms)
if (mShakeTimestamp + getSHAKE_SLOP_TIME_MS() > now) {
return;
}
// reset the shake count after 3 seconds of no shakes
if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
mShakeCount = 0;
}
mShakeTimestamp = now;
mShakeCount++;
mListener.onShake(mShakeCount);
}
}
}
private long getSHAKE_SLOP_TIME_MS() {
// TODO Auto-generated method stub
return SHAKE_SLOP_TIME_MS;
}
public void setSHAKE_SLOP_TIME_MS(int sHAKE_SLOP_TIME_MS) {
SHAKE_SLOP_TIME_MS = sHAKE_SLOP_TIME_MS;
}
}
A HashSet
holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here
HashSet
is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet
also provides standard set operations such as union, intersection, and symmetric difference. Take a look here
There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However, that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.
The HashSet
class in C# goes for the first approach, thus not preserving the order of elements. It is much faster than a regular List
. Some basic benchmarks showed that HashSet is decently faster when dealing with primary types (int, double, bool, etc.). It is a lot faster when working with class objects. So that point is that HashSet is fast.
The only catch of HashSet
is that there is no access by indices. To access elements you can either use an enumerator or use the built-in function to convert the HashSet
into a List
and iterate through that. Take a look here
Besides listing the files explicitly as shown by unwind and Wienczny, you can setup change lists and checkin these. These allow you to manage disjunct sets of changes to the same working copy.
You can read about them in the online version of the excellent SVN book.
Newer versions of svn support the --show-item
argument:
svn info --show-item revision
For the revision number of your local working copy, use:
svn info --show-item last-changed-revision
You can use os.system()
to execute a command line like this:
svn info | grep "Revision" | awk '{print $2}'
I do that in my nightly build scripts.
Also on some platforms there is a svnversion
command, but I think I had a reason not to use it. Ahh, right. You can't get the revision number from a remote repository to compare it to the local one using svnversion.
Hope this is something what you are trying to do :
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
private Map ttp = new HashMap();
public void test() {
Field declaredField = null;
try {
declaredField = Test.class.getDeclaredField("ttp");
boolean accessible = declaredField.isAccessible();
declaredField.setAccessible(true);
ConcurrentHashMap<Object, Object> concHashMap = new ConcurrentHashMap<Object, Object>();
concHashMap.put("key1", "value1");
declaredField.set(this, concHashMap);
Object value = ttp.get("key1");
System.out.println(value);
declaredField.setAccessible(accessible);
} catch (NoSuchFieldException
| SecurityException
| IllegalArgumentException
| IllegalAccessException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
Test test = new Test();
test.test();
}
}
It prints :
value1
Swift 4:
Perfectly working code to change the navigation bar appearance at application level.
// MARK: Navigation Bar Customisation
// To change background colour.
UINavigationBar.appearance().barTintColor = .init(red: 23.0/255, green: 197.0/255, blue: 157.0/255, alpha: 1.0)
// To change colour of tappable items.
UINavigationBar.appearance().tintColor = .white
// To apply textAttributes to title i.e. colour, font etc.
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : UIColor.white,
.font : UIFont.init(name: "AvenirNext-DemiBold", size: 22.0)!]
// To control navigation bar's translucency.
UINavigationBar.appearance().isTranslucent = false
Happy Coding!
Since you are open to jQuery, this plugin seems to do the trick.
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
Following are the build-in constants you can use as per your requirements for getting the paths in Codeigniter:
EXT: The PHP file extension
FCPATH: Path to the front controller (this file) (root of CI)
SELF: The name of THIS file (index.php)
BASEPATH: Path to the system folder
APPPATH: The path to the “application” folder
Thanks.
If you're talking about PL/SQL, you should put it in an anonymous block.
DECLARE
v_text VARCHAR2(10); -- declare
BEGIN
v_text := 'Hello'; --assign
dbms_output.Put_line(v_text); --display
END;
There are practical two ways to do this automaticly while only one solution can be used in all browsers. First of all you should use the open xml specification to build the excel sheet. There are free plugins from Microsoft available that make this format also available for older office versions. The open xml is standard since office 2007. The the two ways are obvious the serverside or the clientside.
The clientside implementation use a new standard of CSS that allow you to store data instead of just the URL to the data. This is a great approach coz you dont need any servercall, just the data and some javascript. The killing downside is that microsoft don't support all parts of it in the current IE (I don't know about IE9) releases. Microsoft restrict the data to be a image but we will need a document. In firefox it works quite fine. For me the IE was the killing point.
The other way is to user a serverside implementation. There should be a lot implementations of open XML for all languages. You just need to grap one. In most cases it will be the simplest way to modify a Viewmodel to result in a Document but for sure you can send all data from Clientside back to server and do the same.
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
If your are invoking fetch on a localhost server, use non-SSL unless you have a valid certificate for localhost. fetch will fail on an invalid or self signed certificate especially on localhost.
i set my bind-address correctly as above but forgot to restart the mysql server (or reboot) :) face palm - so that's the source of this error for me!
One technique I think is a little easier and that hasn't been mentioned before here:
var asdf = new [] {
(Age: 1, Name: "cow"),
(Age: 2, Name: "bird")
}.ToList();
I think that's a little cleaner than:
var asdf = new List<Tuple<int, string>> {
(Age: 1, Name: "cow"),
(Age: 2, Name: "bird")
};
Well, you can stick one or more "soft hyphens" (­
) in your long unbroken strings. I doubt that old IE versions deal with that correctly, but what it's supposed to do is tell the browser about allowable word breaks that it can use if it has to.
Now, how exactly would you pick where to stuff those characters? That depends on the actual string and what it means, I guess.
I saw a more concise method of getting Array.prototype
methods in general that works just as well. Converting an HTMLCollection
object into an Array
object is demonstrated below:
[].slice.call( yourHTMLCollectionObject );
And, as mentioned in the comments, for old browsers such as IE7 and earlier, you simply have to use a compatibility function, like:
function toArray(x) {
for(var i = 0, a = []; i < x.length; i++)
a.push(x[i]);
return a
}
I know this is an old question, but I felt the accepted answer was a little incomplete; so I thought I'd throw this out there FWIW.
For those interested, here's an alternative to invoking Array.join:
var arrayOfStrings = ['foo', 'bar'];
var result = String.concat.apply(null, arrayOfStrings);
console.log(result);
The output, as expected, is the string 'foobar'. In Firefox, this approach outperforms Array.join but is outperformed by + concatenation. Since String.concat requires each segment to be specified as a separate argument, the caller is limited by any argument count limit imposed by the executing JavaScript engine. Take a look at the documentation of Function.prototype.apply() for more information.
Alternative: Check out the code in SVN to some folder
Firstly, understand that DateTime
objects aren't formatted. They just store the Year, Month, Day, Hour, Minute, Second, etc as a numeric value and the formatting occurs when you want to represent it as a string somehow. You can compare DateTime
objects without formatting them.
To compare an input date with DateTime.Now
, you need to first parse the input into a date and then compare just the Year/Month/Day portions:
DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
throw new ArgumentException("Input string not in the correct format.");
if(inputDate.Date == DateTime.Now.Date) {
// Same date!
}
You can turn on your PHP errors with error_reporting
:
error_reporting(E_ALL);
ini_set('display_errors', 'on');
Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:
Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.
You should set display_errors = 1
in your php.ini
file and restart the server.
I tried this on the command line using
D:\>xcopy myfile.dat xcopytest\test\
and the target directory was properly created.
If not you can create the target dir using the mkdir
command with cmd
's command extensions enabled like
cmd /x /c mkdir "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\"
('/x' enables command extensions in case they're not enabled by default on your system, I'm not that familiar with cmd
)
use
cmd /?
mkdir /?
xcopy /?
for further information :)
You can use the following function, which is the modified code of @mvallebr. It respects the properties file comments, ignores empty new lines, and allows retrieving a single key value.
def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
"""
Reads a .properties file and returns the key value pairs as dictionary.
if key value is specified, then it will return its value alone.
"""
with open(propertiesFile) as f:
l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
d = {key.strip(): value.strip() for key, value in l}
if key:
return d[key]
else:
return d
I have another option in this situation. My list is objList, and I have to order but nulls must be in the end. my decision:
var newList = objList.Where(m=>m.Column != null)
.OrderBy(m => m.Column)
.Concat(objList.where(m=>m.Column == null));
From the doc :
Capturing groups</a> are indexed from left
* to right, starting at one. Group zero denotes the entire pattern, so
* the expression m.group(0) is equivalent to m.group().
So capture group 0 send the whole line.
The code should instead be something like this:
TextView text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("test");
Also use NVL2
as below if you want to return other value from the field_to_check
:
NVL2( field_to_check, value_if_NOT_null, value_if_null )
Usage: ORACLE/PLSQL: NVL2 FUNCTION
To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow
<input id="txtDay" type="text" placeholder="DD" />
<input id="txtMonth" type="text" placeholder="MM" />
<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>
function validateDate() {
var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);
if (date == "Invalid Date") {
alert("jnvalid date");
}
}
My suggestion is to use a function. But rather than putting the if
in the function, which you might be tempted to do, do it like this:
if verbose:
def verboseprint(*args):
# Print each argument separately so caller doesn't need to
# stuff everything to be printed into a single string
for arg in args:
print arg,
print
else:
verboseprint = lambda *a: None # do-nothing function
(Yes, you can define a function in an if
statement, and it'll only get defined if the condition is true!)
If you're using Python 3, where print
is already a function (or if you're willing to use print
as a function in 2.x using from __future__ import print_function
) it's even simpler:
verboseprint = print if verbose else lambda *a, **k: None
This way, the function is defined as a do-nothing if verbose mode is off (using a lambda), instead of constantly testing the verbose
flag.
If the user could change the verbosity mode during the run of your program, this would be the wrong approach (you'd need the if
in the function), but since you're setting it with a command-line flag, you only need to make the decision once.
You then use e.g. verboseprint("look at all my verbosity!", object(), 3)
whenever you want to print a "verbose" message.
Try this code for the 24 hrs format of time.
<script type="text/javascript">
var a="12:23:35";
var b="15:32:12";
var aa1=a.split(":");
var aa2=b.split(":");
var d1=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa1[0],10),parseInt(aa1[1],10),parseInt(aa1[2],10));
var d2=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa2[0],10),parseInt(aa2[1],10),parseInt(aa2[2],10));
var dd1=d1.valueOf();
var dd2=d2.valueOf();
if(dd1<dd2)
{alert("b is greater");}
else alert("a is greater");
}
</script>
Use String#slice
, also aliased as []
.
a = "hello there"
a[1] #=> "e"
a[1,3] #=> "ell"
a[1..3] #=> "ell"
a[6..-1] #=> "there"
a[6..] #=> "there" (requires Ruby 2.6+)
a[-3,2] #=> "er"
a[-4..-2] #=> "her"
a[12..-1] #=> nil
a[-2..-4] #=> ""
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a["lo"] #=> "lo"
a["bye"] #=> nil
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
Jack M. is right. Do it this way:
>>> class City:
... def __init__(self, city=None):
... self.city = city
... def __repr__(self):
... if self.city: return self.city
... return ''
...
>>> c = City('Berlin')
>>> print c
Berlin
>>> c = City()
>>> print c
>>>
Just because no-one else has posted this opinion, I would say
avoid
else
clauses intry/excepts
because they're unfamiliar to most people
Unlike the keywords try
, except
, and finally
, the meaning of the else
clause isn't self-evident; it's less readable. Because it's not used very often, it'll cause people that read your code to want to double-check the docs to be sure they understand what's going on.
(I'm writing this answer precisely because I found a try/except/else
in my codebase and it caused a wtf moment and forced me to do some googling).
So, wherever I see code like the OP example:
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
else:
# do some more processing in non-exception case
return something
I would prefer to refactor to
try:
try_this(whatever)
except SomeException as the_exception:
handle(the_exception)
return # <1>
# do some more processing in non-exception case <2>
return something
<1> explicit return, clearly shows that, in the exception case, we are finished working
<2> as a nice minor side-effect, the code that used to be in the else
block is dedented by one level.
# Trim whitespace from both ends of specified parameter
trim () {
read -rd '' $1 <<<"${!1}"
}
# Unit test for trim()
test_trim () {
local foo="$1"
trim foo
test "$foo" = "$2"
}
test_trim hey hey &&
test_trim ' hey' hey &&
test_trim 'ho ' ho &&
test_trim 'hey ho' 'hey ho' &&
test_trim ' hey ho ' 'hey ho' &&
test_trim $'\n\n\t hey\n\t ho \t\n' $'hey\n\t ho' &&
test_trim $'\n' '' &&
test_trim '\n' '\n' &&
echo passed
Lines 1,2,3,4 will call the default constructor. They are different in the essence as 1,2 are dynamically created object and 3,4 are statically created objects.
In Line 7, you create an object inside the argument call. So its an error.
And Lines 5 and 6 are invitation for memory leak.
Forget datalist element that good solution for autocomplete function, but not for combobox feature.
css:
.combobox {
display: inline-block;
position: relative;
}
.combobox select {
display: none;
position: absolute;
overflow-y: auto;
}
html:
<div class="combobox">
<input type="number" name="" value="" min="" max="" step=""/><br/>
<select size="3">
<option value="0"> 0</option>
<option value="25"> 25</option>
<option value="40"> 40</option>
</select>
</div>
js (jQuery):
$('.combobox').each(function() {
var
$input = $(this).find('input'),
$select = $(this).find('select');
function hideSelect() {
setTimeout(function() {
if (!$select.is(':focus') && !$input.is(':focus')) {
$select
.hide()
.css('z-index', 1);
}
}, 20);
}
$input
.focusin(function() {
if (!$select.is(':visible')) {
$select
.outerWidth($input.outerWidth())
.show()
.css('z-index', 100);
}
})
.focusout(hideSelect)
.on('input', function() {
$select.val('');
});
$select
.change(function() {
$input.val($select.val());
})
.focusout(hideSelect);
});
This works properly even when you use text input instead of number.
It's not a standard lib of python 2.7. So in order for these to work properly and if you're using Python 2.7 you should download the PIL library first: Direct download link: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe After installing it, follow these steps:
Edit your script.py
from Tkinter import *
from PIL import ImageTk, Image
app_root = Tk()
#Setting it up
img = ImageTk.PhotoImage(Image.open("app.png"))
#Displaying it
imglabel = Label(app_root, image=img).grid(row=1, column=1)
app_root.mainloop()
Hope that helps!
Converting String to Json Object by using org.json.simple.JSONObject
private static JSONObject createJSONObject(String jsonString){
JSONObject jsonObject=new JSONObject();
JSONParser jsonParser=new JSONParser();
if ((jsonString != null) && !(jsonString.isEmpty())) {
try {
jsonObject=(JSONObject) jsonParser.parse(jsonString);
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}
return jsonObject;
}
Here are some I can think about :
bindParam
, you can only pass variables ; not valuesbindValue
, you can pass both (values, obviously, and variables)bindParam
works only with variables because it allows parameters to be given as input/output, by "reference" (and a value is not a valid "reference" in PHP) : it is useful with drivers that (quoting the manual) : support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.
With some DB engines, stored procedures can have parameters that can be used for both input (giving a value from PHP to the procedure) and ouput (returning a value from the stored proc to PHP) ; to bind those parameters, you've got to use bindParam, and not bindValue.
Another valuable option would be https://github.com/ThomasMcDonald/Localhost-uri-Redirector. It's a very simple html page that redirects to whatever host and port you configure in the UI.
The page is hosted on Github https://thomasmcdonald.github.io/Localhost-uri-Redirector, so you can use that as your OAuth2 redirect url and configure you target host and port in the UI and it will just redirect to your app
For windows I found that when i loaded the filles(jd2xsx.dll calls & ftd2xx.dll) into the windowws/system32 folder this resolved the issues. I then had an issue with my newer fd2xx.dll having to do with parameters which is why I had to load the older version of this dll. I will have to ferrit this out later.
Note: the jd2xsx.dll calls the ftd2xx.dll so just setting the path for the jd2xx.dll might not work.
You can use simple linq query as follow to select all records from sql table
var qry = ent.tableName.Select(x => x).ToList();
If you are using the VSCodeVim
extension, you can use the Vim key shortcuts:
Next tab: gt
Prior tab: gT
Numbered tab: nnngt
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
Edit
For angular 6.1 and newer, use the KeyValuePipe as suggested by Londeren.
For angular 6.0 and older
To make things easier, you can create a pipe.
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'getValues'})
export class GetValuesPipe implements PipeTransform {
transform(map: Map<any, any>): any[] {
let ret = [];
map.forEach((val, key) => {
ret.push({
key: key,
val: val
});
});
return ret;
}
}
<li *ngFor="let recipient of map |getValues">
As it it pure, it will not be triggered on every change detection, but only if the reference to the map
variable changes
INNER JOIN gets all records that are common between both tables based on the supplied ON clause.
LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.
RIGHT JOIN is like the above but gets all records in the RIGHT table.
FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.
Select all text afected by this issue:
Window -> Character, click the icon next to hide the Character Window, Middle Western Features and select Left-to-right character direction.
I like...
@data = `cat /var/tmp/somefile`;
It's not as glamorous as others, but, it works all the same. And...
$todays_data = '/var/tmp/somefile' ;
open INFILE, "$todays_data" ;
@data = <INFILE> ;
close INFILE ;
Cheers.
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
This function will prevent entry of anything other than numbers and a single dot.
function validateQty(el, evt) {_x000D_
var charCode = (evt.which) ? evt.which : event.keyCode_x000D_
if (charCode != 45 && charCode != 8 && (charCode != 46) && (charCode < 48 || charCode > 57))_x000D_
return false;_x000D_
if (charCode == 46) {_x000D_
if ((el.value) && (el.value.indexOf('.') >= 0))_x000D_
return false;_x000D_
else_x000D_
return true;_x000D_
}_x000D_
return true;_x000D_
var charCode = (evt.which) ? evt.which : event.keyCode;_x000D_
var number = evt.value.split('.');_x000D_
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {_x000D_
return false;_x000D_
}_x000D_
};
_x000D_
<input type="text" onkeypress='return validateQty(this,event);'>
_x000D_
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:
var startTimeout = function(timeout, i){
setTimeout(function() {
myAsyncFunc(i).then(function(data){
console.log(data);
})
}, timeout);
}
var myFunc = function(){
timeout = 0;
i = 0;
while(i < 10){
// By calling a function, the i-value is going to be 1.. 10 and not always 10
startTimeout(timeout, i);
// Increase timeout by 1 sec after each call
timeout += 1000;
i++;
}
}
This examples waits 1 second after each request before sending the next one.
As of now, Installing the apks to the /system
directory seems to be working using adb push
command.
Some hidden service was automatically remounting the /system
directory in read-only
mode.
Any way I was able to install the Play store in a normal virtual-machine ( Ie, non-Google-Api virtual machine ) by simply mounting the system.img
file from my OS and by copying over the files.
# To be executed as root user in your Unix based OS
mkdir sys_temp
mount $SDK_HOME/system-images/android-23/default/x86/system.img sys_temp -o loop
cp Phonesky.apk GmsCore.apk GoogleLoginService.apk GoogleServicesFramework.apk ./sys_temp/priv-app/
umount sys_temp
rmdir sys_temp
The APK files can be pulled from any real Android device running Google Apps by using adb pull
command
[ To get the exact path of the apks, we can use command
pm list packages -f
inside the adb shell ]
Just use your table inside a div with a class (.table1
for example) and don't set any border for this table in CSS. Then use CSS code for that class.
.table1 {border=1px solid black;}
The error usually gets introduced while creation of CSV. Try using Linux for saving the CSV as a TextCSV. Libre Office in Ubuntu can enforce the encoding to be UTF-8, worked for me. I wasted a lot of time trying this on Mac OS. Linux is the key. I've tested on Ubuntu.
Good Luck
Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.
To be more specific if you literally want to retrieve Text of Selected Item then you can write:
ListBox1.SelectedItem.Text;
Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.
Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use
ListBox1.SelectedValue
JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm
page.
One idea is to let the the browser know that it should redirect by adding a redirect
variable to to the resulting object and checking for it in JQuery:
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "populateData.htm",
dataType:"json",
data:"userId=SampleUser",
success:function(response){
if (response.redirect) {
window.location.href = response.redirect;
}
else {
// Process the expected results...
}
},
error: function(xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
});
You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1")
and in JQuery you do on success(!):
//....
success:function(response){
if (response.getResponseHeader('REQUIRES_AUTH') === '1'){
window.location.href = 'login.htm';
}
else {
// Process the expected results...
}
}
//....
Hope that helps.
My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.
According to last row on the Date and Time Patterns table of the Java 7 API
X Time zone ISO 8601 time zone -08; -0800; -08:00
For ISO 8601 time zone you should use:
so to parse your "2010-04-05T17:16:00Z" you can use either "yyyy-MM-dd'T'HH:mm:ssX" or "yyyy-MM-dd'T'HH:mm:ssXX" or "yyyy-MM-dd'T'HH:mm:ssXXX" .
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX").parse("2010-04-05T17:16:00Z"));
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").parse("2010-04-05T17:16:00Z"));
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").parse("2010-04-05T17:16:00Z"));
will correctly print out 'Mon Apr 05 13:16:00 EDT 2010'
For your information, the python equivalent is:
imageBuffer = cv.LoadImage( strSrc )
nW = new X size
nH = new Y size
smallerImage = cv.CreateImage( (nH, nW), imageBuffer.depth, imageBuffer.nChannels )
cv.Resize( imageBuffer, smallerImage , interpolation=cv.CV_INTER_CUBIC )
cv.SaveImage( strDst, smallerImage )
The object stored at d[a]
has not been set to anything. Thus, d[a]
evaluates to undefined
. You can't assign a property to undefined
:). You need to assign an object or array to d[a]
:
d[a] = [];
d[a]["greeting"] = b;
console.debug(d);
If your Windows language is different from English, you can launch the Task Scheduler by
private static readonly ICollection<string> PositiveList = new Collection<string> { "Y", "Yes", "T", "True", "1", "OK" };
public static bool ToBoolean(this string input)
{
return input != null && PositiveList.Any(? => ?.Equals(input, StringComparison.OrdinalIgnoreCase));
}
After declaring the array
int boardAux[length][length];
the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy
int i, j;
for (i = 0; i<length; i++)
{
for (j = 0; j<length; j++)
boardAux[i][j] = 0;
}
I asked the same question some time ago and had to answer it myself. Here's what I came up with:
It seems, my first thought [that it comes from its JavaScript roots] was correct.
'\/' === '/'
in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like\z
) not allowed in JSON?The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.
Drops all tables and recreates them:
python manage.py sqlclear app1 app2 appN | sed -n "2,$p" | sed -n "$ !p" | sed "s/";/" CASCADE;/" | sed -e "1s/^/BEGIN;/" -e "$s/$/COMMIT;/" | python manage.py dbshell
python manage.py syncdb
Explanation:
manage.py sqlclear
- "prints the DROP TABLE SQL statements for the given app name(s)"
sed -n "2,$p"
- grabs all lines except first line
sed -n "$ !p"
- grabs all lines except last line
sed "s/";/" CASCADE;/"
- replaces all semicolons (;) with (CASCADE;)
sed -e "1s/^/BEGIN;/" -e "$s/$/COMMIT;/"
- inserts (BEGIN;) as first text, inserts (COMMIT;) as last text
manage.py dbshell
- "Runs the command-line client for the database engine specified in your ENGINE setting, with the connection parameters specified in your USER, PASSWORD, etc., settings"
manage.py syncdb
- "Creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created"
Dependencies:
Credits:
@Manoj Govindan and @Mike DeSimone for sqlclear piped to dbshell
@jpic for 'sed "s/";/" CASCADE;/"'
In Python:
self
argument.self
) or the class (cls
) argument.__init__
is a special function and without overriding __new__
it will always be given the instance of the class as its first argument.
An example using the builtin classmethod and staticmethod decorators:
import sys
class Num:
max = sys.maxint
def __init__(self,num):
self.n = num
def getn(self):
return self.n
@staticmethod
def getone():
return 1
@classmethod
def getmax(cls):
return cls.max
myObj = Num(3)
# with the appropriate decorator these should work fine
myObj.getone()
myObj.getmax()
myObj.getn()
That said, I would try to use @classmethod
/@staticmethod
sparingly. If you find yourself creating objects that consist of nothing but staticmethod
s the more pythonic thing to do would be to create a new module of related functions.
Just change the port number used e.g. 8000 then call the http://localhost:8080
void 0
mean?void
[MDN] is a prefix keyword that takes one argument and always returns undefined
.
Examples
void 0
void (0)
void "hello"
void (new Date())
//all will return undefined
It seems pretty useless, doesn't it? If it always returns undefined
, what's wrong with just using undefined
itself?
In a perfect world we would be able to safely just use undefined
: it's much simpler and easier to understand than void 0
. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.
The problem with using undefined
was that undefined
is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined
is a permissible variable name, so you could assign a new value to it at your own caprice.
alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"
Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined
property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.
alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"
void
, on the other hand, cannot be overidden. void 0
will always return undefined
. undefined
, on the other hand, can be whatever Mr. Javascript decides he wants it to be.
void 0
, specifically?Why should we use void 0
? What's so special about 0
? Couldn't we just as easily use 1
, or 42
, or 1000000
or "Hello, world!"
?
And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0
instead of some other argument is that 0
is short and idiomatic.
Although undefined
can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0
: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined
with void 0
to reduce the number of bytes sent to the browser.
Expression: "Total Count: " + (DT_WSTR, 11)@[User::int32Value]
for Int32 -- (-2,147,483,648 to 2,147,483,647)
I had the same problem. I looked into my complied dll with reflector and have seen that the name of the resource was not right. I renamed and it looks fine now.
So the problem must be with your JCE Unlimited Strength installation.
Be sure you overwrite the local_policy.jar
and US_export_policy.jar
in both your JDK's jdk1.6.0_25\jre\lib\security\
and in your JRE's lib\security\
folder.
In my case I would place the new .jars in:
C:\Program Files\Java\jdk1.6.0_25\jre\lib\security
and
C:\Program Files\Java\jre6\lib\security
If you are running Java 8 and you encounter this issue. Below steps should help!
Go to your JRE installation (e.g - jre1.8.0_181\lib\security\policy\unlimited) copy local_policy.jar and replace it with 'local_policy.jar' in your JDK installation directory (e.g - jdk1.8.0_141\jre\lib\security).
django
is smart enough. Actually we don't need to define oneToMany
field. It will be automatically generated by django
for you :-). We only need to define foreignKey
in related table. In other words, we only need to define ManyToOne
relation by using foreignKey
.
class Car(models.Model):
// wheels = models.oneToMany() to get wheels of this car [**it is not required to define**].
class Wheel(models.Model):
car = models.ForeignKey(Car, on_delete=models.CASCADE)
if we want to get the list of wheels of particular car. we will use python's
auto generated object wheel_set
. For car c
you will use c.wheel_set.all()
android:layout_weight=".YOURVALUE" is best way to implement in percentage
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/logTextBox"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".20"
android:maxLines="500"
android:scrollbars="vertical"
android:singleLine="false"
android:text="@string/logText" >
</TextView>
</LinearLayout>
Setting a min-width on child elements will also create a breakpoint. For example breaking every 3 elements,
flex-grow: 1;
min-width: 33%;
If there are 4 elements, this will have the 4th element wrap taking the full 100%. If there are 5 elements, the 4th and 5th elements will wrap and take each 50%.
Make sure to have parent element with,
flex-wrap: wrap
In my case the image file had just been written to and needed to be flushed before opening, like so:
img_file.flush()
img = Image.open(img_file.name))
HTML--
<div class="col-sm-12" id="my_styles">
<button type="submit" class="btn btn-warning" id="1">Button1</button>
<button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>
css--
.active{
background:red;
}
button.btn:active{
background:red;
}
jQuery--
jQuery("#my_styles .btn").click(function(){
jQuery("#my_styles .btn").removeClass('active');
jQuery(this).toggleClass('active');
});
view the live demo on jsfiddle
I had this issue this weekend. It seems to have happened because I opened my project in my venv, but I also opened a second instance outside of the venv. I never closed either instance - I just shut my PC down and let Windows do the work. When I went back and called up Visual Studio Code from within my venv, both the project, and the other non-venv window opened. That's when I started seeing this error.
To fix it, I had to remove the \.vscode
folder from the workspace directory.
I don't think it is in the java API. but most datatypes which have a number of elements in it, have a size()
method. I think you can easily write a function to check for size yourself?
Just use it as you would a non-concurrent collection. The Concurrent[Collection] classes wrap the regular collections so that you don't have to think about synchronizing access.
Edit: ConcurrentLinkedList isn't actually just a wrapper, but rather a better concurrent implementation. Either way, you don't have to worry about synchronization.
extern keyword is used with the variable for its identification as a global variable.
It also represents that you can use the variable declared using extern keyword in any file though it is declared/defined in other file.
I took some time to check it in detail. I created an icon whose images have sizes of 16, 24, 32, 40, 48, 64, 96, 128 and 256. Then I checked which image is shown. All these were done with normal 96dpi. If using a larger DPI, the larger sizes may be used (only checked this a bit in Windows 7). The results:
Windows XP:
Windows 7:
Windows Runtime: (from here)
So the result: Windows XP uses 16, 32, 48-size icons, while Windows 7 (and presumably also Vista) also uses 256-size icons. All other intermediate icon sizes are ignored (they may be used in some area which I didn't check).
I also checked in Windows 7 what happens if icon sizes are missing:
The missing sizes are generated (obviously). With sizes of 16, 32, and 48, if one is missing, downscaling is preferred. So if we have icons with size 16 and 48, the 32 icon is created from the 48 icon. The 256 icon is only used for these if no other sizes are available! So if the icons are size 16 and 256, the other sizes are upscaled from the 16 icon!
Additionally, if the 256 icon is not there, the (possibly generated) 48 icon is used, but not resized anymore. So we have a (possibly large) empty area with the 48 icon in the middle.
Note that the default desktop icon size in XP was 32x32, while in Windows 7 it is 48x48. As a consequence, for Windows 7 it is relatively important to have a 48 icon. Otherwise, it is upscaled from a smaller icon, which may look quite ugly.
Just a note about Windows XP compatibility: If you reuse the icon as window icon, then note that this can crash your application if you use a compressed 256 icon. The solution is to either not compress the icon or create a second version without the (compressed) 256 icon. See here for more info.
To add to add to the previous answer, there is even a fourth way that can be used
import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)
try it proxy package.json add code:
"proxy":"https://localhost:port"
and restart npm enjoy
same code
const instance = axios.create({
baseURL: "/api/list",
});
Ideally, Windows authentication must be used when working in an Intranet type of an environment.
Whereas, SQL Server authentication can be used in all the other type of cases.
Here is a link which might help.
I also have the issue because of i have compile 'com.android.support:appcompat-v7:24.0.0-alpha1' but i added recyclerview liberary compile 'com.android.support:recyclerview-v7:24.0.2'..i changed the version as same as compat like (24.0.2 intead of 24.0.0).
i got the answer..may be it will help for someone.
def revstr(a):
b=''
if len(a)%2==0:
for i in range(0,len(a),2):
b += a[i + 1] + a[i]
a=b
else:
c=a[-1]
for i in range(0,len(a)-1,2):
b += a[i + 1] + a[i]
b=b+a[-1]
a=b
return b
a=raw_input('enter a string')
n=revstr(a)
print n
I recommend using pyenv to manage your local python versions (both 2.x and 3.x) instead of installing new versions directly with homebrew or building new python versions from source manually. Essentially, pyenv
can do two key things for you:
pyenv install 3.8.1
will install python 3.8.1 under ~/.pyenv/versions/3.8.1
.PATH
) with shims so that when you do pyenv local 3.8.1
, calling python
will invoke the new interpreter instead of your system python.The pyenv
repo is pretty detailed on how to install for different systems and what it's actually doing, but here's the basic steps for mac:
homebrew
if you don't already have it and use it to install pyenv
with brew install pyenv
.bash_profile
file to include:if command -v pyenv 1>/dev/null 2>&1; then
eval "$(pyenv init -)"
fi
Now install some python using pyenv and then switch to it with the pyenv local
command (you can see all your versions with pyenv versions
).
pyenv install 3.8.1 && pyenv local 3.8.1
Note: you may need to create a new shell or reload your bash_profile
in your current shell for the pyenv initialization to do its thing (set up shims).
With this setup, you'll be able to keep your system macosx python and switch to whatever new version of python you want available through pyenv
.
There is solution for you :)
You must run your script after window loaded
if you use jQuery, you can use simple way:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
status : true,
version : 'v2.5'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<script>
$(window).load(function() {
var comment_callback = function(response) {
console.log("comment_callback");
console.log(response);
}
FB.Event.subscribe('comment.create', comment_callback);
FB.Event.subscribe('comment.remove', comment_callback);
});
</script>
Code for background image of a Button in Swift 3.0
buttonName.setBackgroundImage(UIImage(named: "facebook.png"), for: .normal)
Hope this will help someone.
In my case (im using Firebase Cloud Functions) i opened .eslintrc.json
and changed:
"parserOptions": {
// Required for certain syntax usages
"ecmaVersion": 2017
},
to:
"parserOptions": {
// Required for certain syntax usages
"ecmaVersion": 2020
},
Here's a more comprehensive solution to the disconnect selection, and the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)
(function($){
$.fn.ctrlCmd = function(key) {
var allowDefault = true;
if (!$.isArray(key)) {
key = [key];
}
return this.keydown(function(e) {
for (var i = 0, l = key.length; i < l; i++) {
if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
allowDefault = false;
}
};
return allowDefault;
});
};
$.fn.disableSelection = function() {
this.ctrlCmd(['a', 'c']);
return this.attr('unselectable', 'on')
.css({'-moz-user-select':'-moz-none',
'-moz-user-select':'none',
'-o-user-select':'none',
'-khtml-user-select':'none',
'-webkit-user-select':'none',
'-ms-user-select':'none',
'user-select':'none'})
.bind('selectstart', false);
};
})(jQuery);
and call example:
$(':not(input,select,textarea)').disableSelection();
This could be also not enough for old versions of FireFox (I can't tell which). If all this does not work, add the following:
.on('mousedown', false)
Do a git status
to find out if your file is actually in your index or the commit.
It is easy as a beginner to misunderstand the index/staging area.
I view it as a 'progress pinboard'. I therefore have to add
the file to the pinboard before I can commit
it (i.e. a copy of the complete pinboard), I have to update the pinboard when required, and I also have to deliberately remove files from it when I've finished with them - simply creating, editing or deleting a file doesn't affect the pinboard. It's like 'storyboarding'.
Edit: As others noted, You should do the edits locally and then push the updated repo, rather than attempt to edit directly on github.
Perhaps you should check NLS_DATE_FORMAT
and use the date string conforming the format.
Or you can use to_date
function within the INSERT
statement, like the following:
insert into visit
values(123456,
to_date('19-JUN-13', 'dd-mon-yy'),
to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));
Additionally, Oracle DATE
stores date and time information together.
Just because this is what I got when I Googled this error, my problem was that I had
if (value < other.value)
return -1;
else if (value >= other.value)
return 1;
else
return 0;
the value >= other.value
should (obviously) actually be value > other.value
so that you can actually return 0 with equal objects.
Just change the class (I suppose it's the main Activity) to implement View.OnClickListener and on the onClick method put the general onClick actions you want to put:
public class MediaPlayer extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
Button b1 = (Button) findViewById(R.id.buttonplay);
b1.setOnClickListener(this);
//{YOUR APP}
}
@Override
public void onClick(View v) {
// Perform action on click
switch(v.getId()) {
case R.id.buttonplay:
//Play voicefile
MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
break;
case R.id.buttonstop:
//Stop MediaPlayer
MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
break;
}
}}
I took it from this video: http://www.youtube.com/watch?v=rm-hNlTD1H0 . It's good for starters.
Apply style="text-align: right"
to the input tag. This will allow entry to be right-justified, and (at least in Firefox 3, IE 7 and Safari) will even appear to flow from the right.
http://www.movable-type.co.uk/scripts/aes.html library may be of some help.
According to React's Documentation, you can write comments in JSX like so:
One-line Comment:
<div>
{/* Comment goes here */}
Hello, {name}!
</div>
Multi-line Comments:
<div>
{/* It also works
for multi-line comments. */}
Hello, {name}!
</div>
@SuppressWarnings("deprecation")
public static void forceLocale(Context context, String localeCode) {
String localeCodeLowerCase = localeCode.toLowerCase();
Resources resources = context.getApplicationContext().getResources();
Configuration overrideConfiguration = resources.getConfiguration();
Locale overrideLocale = new Locale(localeCodeLowerCase);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
overrideConfiguration.setLocale(overrideLocale);
} else {
overrideConfiguration.locale = overrideLocale;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
context.getApplicationContext().createConfigurationContext(overrideConfiguration);
} else {
resources.updateConfiguration(overrideConfiguration, null);
}
}
Just use this helper method to force specific locale.
UDPATE 22 AUG 2017. Better use this approach.
Above All answers are perfect. but I am adding which is very good and rapid to generate any random string value
function randomStringGenerator(stringLength) {_x000D_
var randomString = ""; // Empty value of the selective variable_x000D_
const allCharacters = "'`~!@#$%^&*()_+-={}[]:;\'<>?,./|\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'"; // listing of all alpha-numeric letters_x000D_
while (stringLength--) {_x000D_
randomString += allCharacters.substr(Math.floor((Math.random() * allCharacters.length) + 1), 1); // selecting any value from allCharacters varible by using Math.random()_x000D_
}_x000D_
return randomString; // returns the generated alpha-numeric string_x000D_
}_x000D_
_x000D_
console.log(randomStringGenerator(10));//call function by entering the random string you want
_x000D_
or
console.log(Date.now())// it will produce random thirteen numeric character value every time._x000D_
console.log(Date.now().toString().length)// print length of the generated string
_x000D_
I would suggest going the lxml route and using xpath.
from lxml import etree
# data is the variable containing the html
data = etree.HTML(data)
anchor = data.xpath('//a[@class="title"]/text()')
Using history.listen
For example like below:
In your component,
componentWillMount() {
this.props.history.listen(() => {
// Detecting, user has changed URL
console.info(this.props.history.location.pathname);
});
}
The problem here is twofold
fgetc()
returns an int instead of a char.The first is easily fixed:
char *orig = code; // the beginning of the array
// ...
do {
*code = fgetc(file);
} while(*code++ != EOF);
*code = '\0'; // nul-terminate the string
return orig; // don't return a pointer to the end
The second problem is more subtle -fgetc
returns an int so that the EOF
value can be distinguished from any possible char value. Fixing this uses a temporary int for the EOF
check and probably a regular while loop instead of do / while.
The compiler is confused by the function signature. You can fix it like this:
let task = URLSession.shared.dataTask(with: request as URLRequest) {
But, note that we don't have to cast "request" as URLRequest
in this signature if it was declared earlier as URLRequest
instead of NSMutableURLRequest
:
var request = URLRequest(url:myUrl!)
This is the automatic casting between NSMutableURLRequest
and the new URLRequest
that is failing and which forced us to do this casting here.
I spent 3 months working on a solution to the 10 best point dense 5x5 Boggle boards problem.
The problem is now solved and laid out with full disclosure on 5 web pages. Please contact me with questions.
The board analysis algorithm uses an explicit stack to pseudo-recursively traverse the board squares through a Directed Acyclic Word Graph with direct child information, and a time stamp tracking mechanism. This may very well be the world's most advanced lexicon data structure.
The scheme evaluates some 10,000 very good boards per second on a quad core. (9500+ points)
Parent Web Page:
DeepSearch.c - http://www.pathcom.com/~vadco/deep.html
Component Web Pages:
Optimal Scoreboard - http://www.pathcom.com/~vadco/binary.html
Advanced Lexicon Structure - http://www.pathcom.com/~vadco/adtdawg.html
Board Analysis Algorithm - http://www.pathcom.com/~vadco/guns.html
Parallel Batch Processing - http://www.pathcom.com/~vadco/parallel.html
- This comprehensive body of work will only interest a person who demands the very best.
From my point of view,
Correct rounding is likely desired.
Therefore math.Round() is your quick(!) friend. Approaches with fmt.Sprintf and strconv.Atois() were 2 orders of magnitude slower according to my tests with a matrix of float64 values that were intended to become correctly rounded int values.
package main
import (
"fmt"
"math"
)
func main() {
var x float64 = 5.51
var y float64 = 5.50
var z float64 = 5.49
fmt.Println(int(math.Round(x))) // outputs "6"
fmt.Println(int(math.Round(y))) // outputs "6"
fmt.Println(int(math.Round(z))) // outputs "5"
}
math.Round() does return a float64 value but with int() applied afterwards, I couldn't find any mismatches so far.
Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;
SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;
if you try to change color of FAB by using app, there some problem. frame of button have different color, so what you must to do:
app:backgroundTint="@android:color/transparent"
and in code set the color:
actionButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.white)));
if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
{
if(!isset($data[$field]))
$data[$field]="";
}
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
I had this script in app.js in laravel which automatically adds all components in the component folder.
const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key)))
To make it work just add default
const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
java 1.6.0_21 or later, or so...
$ java -XX:+PrintFlagsFinal -version 2>&1 | grep MaxHeapSize
uintx MaxHeapSize := 12660904960 {product}
It looks like the min(1G) has been removed.
Or on Windows using findstr
C:\>java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize
Classes
Structs
Interfaces
Events
Properties
Delegates
Expressions
Statements
Attributes
Literals
Dispose in foreach
foreach over string specialization
C# 2 - Visual Studio 2005
Generics
Partial types
Anonymous methods
Iterators
Nullable types
Getter/setter separate accessibility
Method group conversions (delegates)
Static classes
Delegate inference
Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expression
Expression trees
Partial methods
Dynamic binding
Named and optional arguments
Co- and Contra-variance for generic delegates and interfaces
Embedded interop types ("NoPIA")
Asynchronous methods
Caller info attributes
Draft Specification online
Compiler-as-a-service (Roslyn)
Import of static type members into namespace
Exception filters
Await in catch/finally blocks
Auto property initializers
Default values for getter-only properties
Expression-bodied members
Null propagator (null-conditional operator, succinct null checking)
String interpolation
nameof operator
Dictionary initializer
Out variables
Pattern matching
Tuples
Deconstruction
Discards
Local Functions
Binary Literals
Digit Separators
Ref returns and locals
Generalized async return types
More expression-bodied members
Throw expressions
Async main
Default expressions
Reference assemblies
Inferred tuple element names
Pattern-matching with generics
Span and ref-like types
In parameters and readonly references
Ref conditional
Non-trailing named arguments
Private protected accessibility
Digit separator after base specifier
System.Enum, System.Delegate and unmanaged constraints.
Ref local re-assignment: Ref locals and ref parameters can now be reassigned with the ref assignment operator (= ref).
Stackalloc initializers: Stack-allocated arrays can now be initialized, e.g. Span<int> x = stackalloc[] { 1, 2, 3 };.
Indexing movable fixed buffers: Fixed buffers can be indexed into without first being pinned.
Custom fixed statement: Types that implement a suitable GetPinnableReference can be used in a fixed statement.
Improved overload candidates: Some overload resolution candidates can be ruled out early, thus reducing ambiguities.
Expression variables in initializers and queries: Expression variables like out var and pattern variables are allowed in field initializers, constructor initializers and LINQ queries.
Tuple comparison: Tuples can now be compared with == and !=.
Attributes on backing fields: Allows [field: …] attributes on an auto-implemented property to target its backing field.
Nullable reference types: express nullability intent on reference types with ?, notnull constraint and annotations attributes in APIs, the compiler will use those to try and detect possible null values being dereferenced or passed to unsuitable APIs.
Default interface members: interfaces can now have members with default implementations, as well as static/private/protected/internal members except for state (ie. no fields).
Recursive patterns: positional and property patterns allow testing deeper into an object, and switch expressions allow for testing multiple patterns and producing corresponding results in a compact fashion.
Async streams: await foreach and await using allow for asynchronous enumeration and disposal of IAsyncEnumerable<T> collections and IAsyncDisposable resources, and async-iterator methods allow convenient implementation of such asynchronous streams.
Enhanced using: a using declaration is added with an implicit scope and using statements and declarations allow disposal of ref structs using a pattern.
Ranges and indexes: the i..j syntax allows constructing System.Range instances, the ^k syntax allows constructing System.Index instances, and those can be used to index/slice collections.
Null-coalescing assignment: ??= allows conditionally assigning when the value is null.
Static local functions: local functions modified with static cannot capture this or local variables, and local function parameters now shadow locals in parent scopes.
Unmanaged generic structs: generic struct types that only have unmanaged fields are now considered unmanaged (ie. they satisfy the unmanaged constraint).
Readonly members: individual members can now be marked as readonly to indicate and enforce that they do not modify instance state.
Stackalloc in nested contexts: stackalloc expressions are now allowed in more expression contexts.
Alternative interpolated verbatim strings: @$"..." strings are recognized as interpolated verbatim strings just like $@"...".
Obsolete on property accessors: property accessors can now be individually marked as obsolete.
Permit t is null on unconstrained type parameter
[source] : https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md
You could extend FutureTask
class, and override the done()
method, then add the FutureTask
object to the ExecutorService
, so the done()
method will invoke when the FutureTask
completed immediately.
In my case, simply giving the user permissions on the database fixed it.
So Right click on the database -> Click Properties -> [left hand menu] Click Permissions -> and scroll down to Backup database -> Tick "Grant"
I also found a workaround which seems to work fine with no warnings:
<resources>
<item name="the_name" type="dimen">255%</item>
<item name="another_name" type="dimen">15%</item>
</resources>
Then:
// theName = 2.55f
float theName = getResources().getFraction(R.dimen.the_name, 1, 1);
// anotherName = 0.15f
float anotherName = getResources().getFraction(R.dimen.another_name, 1, 1);
Warning : it only works when you use the dimen from Java code not from xml
And here is a simple Send-MailMessage
example with username/password for anyone looking for just that
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
Does this do what you want?
print range(0, (m+1)*n, n)[1:]
For m=5, n=20
[20, 40, 60, 80, 100]
Or better yet,
>>> print range(n, (m+1)*n, n)
[20, 40, 60, 80, 100]
For Python3+
>>> print(list(range(n, (m+1)*n, n)))
[20, 40, 60, 80, 100]
Simple solution not sure if this has been suggested or not. This also may not work for some things. That being said this is the simple solution below.
new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true}
List<SelectListItem> InvoiceStatusDD = new List<SelectListItem>();
InvoiceStatusDD.Add(new SelectListItem { Value = "0", Text = "All Invoices" });
InvoiceStatusDD.Add(new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true});
InvoiceStatusDD.Add(new SelectListItem { Value = "7", Text = "Client Approved Invoices" });
@Html.DropDownList("InvoiceStatus", InvoiceStatusDD)
You can also do something like this for a database driven select list. you will need to set selected in your controller
@Html.DropDownList("ApprovalProfile", (IEnumerable<SelectListItem>)ViewData["ApprovalProfiles"], "All Employees")
Something like this but better solutions exist this is just one method.
foreach (CountryModel item in CountryModel.GetCountryList())
{
if (item.CountryPhoneCode.Trim() != "974")
{
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });
}
else {
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });
}
}
Cytoscape supports this with its Architecture example which supports dragging elements.
For creating connections, there is the edgehandles extension. It does not yet support editing existing connections. Question.
For editing connection shapes, there is the edge-editing extension. Demo.
The edit-editation extension seems promising, however there is no demo yet.
Use anchors instead:
aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)
These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^
anchor because it's implicit in the .match()
method).
Then, check if the regex did in fact match before trying to access its results:
if aa:
ip = aa.group()
Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:
ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)
Here, the \b
word boundary anchors make sure that the digits don't exceed 3 for each segment.
go to gradle and then to app.buildgradle then set compileSDKVersion to 21 and then if necessary the android studio will download some files
getDay()
returns the day of the week. To get the date, use date.getDate()
. getMonth()
retrieves the month, but month is zero based, so using getMonth()+1
should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC
to the methods (e.g. date.getUTCFullYear()
, date.getUTCHours()
)
var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName();
and hit return.
Many good reasons about how the code looks like. But what about results?
Let's take a look to some C# code and its IL compiled form:
using System;
public class Test {
public static void Main(string[] args) {
if (args.Length == 0) return;
if ((args.Length+2)/3 == 5) return;
Console.WriteLine("hey!!!");
}
}
This simple snippet can be compiled. You can open the generated .exe
file with ildasm
and check what is the result. I won't post all the assembler thing but I'll describe the results.
The generated IL code does the following:
false
, jumps to the code where the second is.true
jumps to the last instruction. (Note: the last instruction is a return).Console.WriteLine
if false
or to the end if this is true
.So it seems that the code will jump to the end. What if we do a normal if with nested code?
using System;
public class Test {
public static void Main(string[] args) {
if (args.Length != 0 && (args.Length+2)/3 != 5)
{
Console.WriteLine("hey!!!");
}
}
}
The results are quite similar in IL instructions. The difference is that before there were two jumps per condition: if false
go to next piece of code, if true
go to the end. And now the IL code flows better and has 3 jumps (the compiler optimized this a bit):
false
, jump to the end.Anyway, the program counter will always jump.
You can use stristr()
or strpos()
. Both return false if nothing is found.
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
List<string> lines = new List<string>();
using (var sr = new StreamReader("file.txt"))
{
while (sr.Peek() >= 0)
lines.Add(sr.ReadLine());
}
i would suggest this... of Groo's answer.
Following is how I draw a checkbox in a table!
| Checkbox Experiments | [ ] unchecked header | [x] checked header |
| ---------------------|:---------------------:|:-------------------:|
| checkbox | [ ] row | [x] row |
Following examples work for me, please note "is_user_defined" NOT "is_table_type"
IF TYPE_ID(N'idType') IS NULL
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
IF not EXISTS (SELECT * FROM sys.types WHERE is_user_defined = 1 AND name = 'idType')
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
For the mouse cursor (with jQuery UI) :
$('#my-modal').draggable({
handle: ".modal-header"
});
For the touch cursor (with jQuery):
var box = null;
var touchobj = null;
var position = {'x':0, 'y':0};
var positionbox = {'x':0, 'y':0};
// init touch
$('.modal-header').on('touchstart', function(e){
box = $(this).closest('.modal-dialog');
touchobj = e.changedTouches[0];
// take position touch cursor
position['x'] = touchobj.pageX;
position['y'] = touchobj.pageY;
//take original position box to move with touch
positionbox['x'] = parseInt(box.css('left'));
positionbox['y'] = parseInt(box.css('top'));
e.preventDefault();
});
// on move touch
$('.modal-header').on('touchmove', function(e){
var dist = {'x':0, 'y':0};
touchobj = e.changedTouches[0];
// we calculate the distance of move
dist['x'] = parseInt(touchobj.clientX) - position['x'];
dist['y'] = parseInt(touchobj.clientY) - position['y'];
// we apply the movement distance on the box
box.css('left', positionbox['x']+dist['x'] +"px");
box.css('top', positionbox['y']+dist['y'] +"px");
e.preventDefault();
});
The addition of the 2 solutions is compatible
Checking for length is a good answer, but you could also account for an "empty" string that is also only whitespace. Not "technically" empty, but if you care to check:
package main
import (
"fmt"
"strings"
)
func main() {
stringOne := "merpflakes"
stringTwo := " "
stringThree := ""
if len(strings.TrimSpace(stringOne)) == 0 {
fmt.Println("String is empty!")
}
if len(strings.TrimSpace(stringTwo)) == 0 {
fmt.Println("String two is empty!")
}
if len(stringTwo) == 0 {
fmt.Println("String two is still empty!")
}
if len(strings.TrimSpace(stringThree)) == 0 {
fmt.Println("String three is empty!")
}
}
The %d
conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.
There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:
if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
printf("got four numbers\n");
Note that this requires whitespace between the input numbers.
If the id is a single 11-digit number, it's best to treat as a string:
char id[12];
if(scanf("%11s", id) == 1)
{
/* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}
Thanks a lot, it works like this:
java -Djava.rmi.server.hostname=xxx.xxx.xxx.xxx -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=25000 -jar myjar.jar
What about
subdir=thesubdir
for fn in $(find $subdir); do
git ls-files --error-unmatch $fn 2>/dev/null >/dev/null;
if [ "$?" = "1" ]; then
continue;
fi
echo "Restoring $fn";
git show HEAD:$fn > $fn;
done
If you are using an MSSQL Server 2008 and above, you can perform your SELECT
query to return json by using the FOR JSON AUTO
clause E.G
SELECT name, surname FROM users FOR JSON AUTO
Will return Json as
[{"name": "Jane","surname": "Doe" }, {"name": "Foo","surname": "Samantha" }, ..., {"name": "John", "surname": "boo" }]
Each line of a batch file will get executed; but only after the previous line has completed. In your case, as soon as it hits the ftp line the ftp program will start and take over user input. When it is closed then the remaining lines will execute. Meaning the username/password are never sent to the FTP program and instead will be fed to the command prompt itself once the ftp program is closed.
Instead you need to pass everything you need on the ftp command line. Something like:
@echo off
echo user MyUserName> ftpcmd.dat
echo MyPassword>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo put %1>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat SERVERNAME.COM
del ftpcmd.dat
This is because .
is a reserved character in regular expression, representing any character.
Instead, we should use the following statement:
String extensionRemoved = filename.split("\\.")[0];
According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource
, as per this line:
java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource
class in it.
If you should need to replace the handle with something else entirely, rather than just restyling it:
$('.slider').append('<div class="my-handle ui-slider-handle"><svg height="18" width="14"><path d="M13,9 5,1 A 10,10 0, 0, 0, 5,17z"/></svg></div>');_x000D_
_x000D_
$('.slider').slider({_x000D_
range: "min",_x000D_
value: 10_x000D_
});
_x000D_
.slider .ui-state-default {_x000D_
background: none;_x000D_
}_x000D_
.slider.ui-slider .ui-slider-handle {_x000D_
width: 14px;_x000D_
height: 18px;_x000D_
margin-left: -5px;_x000D_
top: -4px;_x000D_
border: none;_x000D_
background: none;_x000D_
}_x000D_
.slider {_x000D_
height: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.9.1/jquery-ui.min.js"></script>_x000D_
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />_x000D_
<div class="slider"></div>
_x000D_
Here, the '\n'
left by cin, is creating issues.
do {
system("cls");
manageCustomerMenu();
cin >> choice; #This cin is leaving a trailing \n
system("cls");
switch (choice) {
case '1':
createNewCustomer();
break;
This \n
is being consumed by next getline in createNewCustomer()
. You should use getline instead -
do {
system("cls");
manageCustomerMenu();
getline(cin, choice)
system("cls");
switch (choice) {
case '1':
createNewCustomer();
break;
I think this would resolve the issue.
In case you're dealing with Unicode, sometimes instead of encode('utf-8')
, you can also try to ignore the special characters, e.g.
"??".encode('ascii','ignore')
or as something.decode('unicode_escape').encode('ascii','ignore')
as suggested here.
Not particularly useful in this example, but can work better in other scenarios when it's not possible to convert some special characters.
Alternatively you can consider replacing particular character using replace()
.
At me such error arose after renaming of a folder with the project.
Disabling Instance Run helped, but what if you do not need to disable it?
I deleted all the tags mentioning the old folder name from the file myproject\app\build\intermediates\restart-dex\debug\build-info.xml
The error has disappeared.
as @DLeh says Use rather
var controller = DependencyResolver.Current.GetService<ControllerB>();
But, giving the controller, a controlller context is important especially when you need to access the User
object, Server
object, or the HttpContext
inside the 'child' controller.
I have added a line of code:
controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);
or else you could have used System.Web to acces the current context too, to access Server
or the early metioned objects
NB: i am targetting the framework version 4.6 (Mvc5)
For me, the problem was solved after I removed jar
file from my project. it seems that one of the jar
files inside my project was using an older version of google play services
.
The answers posted here all didn't quite work for me. They mainly skipped signing embedded frameworks (or including the entitlements).
Here's what's worked for me (it assumes that one ipa file exists is in the current directory):
PROVISION="/path/to/file.mobileprovision"
CERTIFICATE="Name of certificate: To sign with" # must be in the keychain
unzip -q *.ipa
rm -rf Payload/*.app/_CodeSignature/
# Replace embedded provisioning profile
cp "$PROVISION" Payload/*.app/embedded.mobileprovision
# Extract entitlements from app
codesign -d --entitlements :entitlements.plist Payload/*.app/
# Re-sign embedded frameworks
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/Frameworks/*
# Re-sign the app (with entitlements)
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/
zip -qr resigned.ipa Payload
# Cleanup
rm entitlements.plist
rm -r Payload/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.ComponentModel;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = lstEmployee.ConvertToDataTable();
}
public static DataTable ConvertToDataTable<T>(IList<T> list) where T : class
{
try
{
DataTable table = CreateDataTable<T>();
Type objType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor property in properties)
{
if (!CanUseType(property.PropertyType)) continue;
row[property.Name] = property.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
return table;
}
catch (DataException ex)
{
return null;
}
catch (Exception ex)
{
return null;
}
}
private static DataTable CreateDataTable<T>() where T : class
{
Type objType = typeof(T);
DataTable table = new DataTable(objType.Name);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(objType);
foreach (PropertyDescriptor property in properties)
{
Type propertyType = property.PropertyType;
if (!CanUseType(propertyType)) continue;
//nullables must use underlying types
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
propertyType = Nullable.GetUnderlyingType(propertyType);
//enums also need special treatment
if (propertyType.IsEnum)
propertyType = Enum.GetUnderlyingType(propertyType);
table.Columns.Add(property.Name, propertyType);
}
return table;
}
private static bool CanUseType(Type propertyType)
{
//only strings and value types
if (propertyType.IsArray) return false;
if (!propertyType.IsValueType && propertyType != typeof(string)) return false;
return true;
}
}
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
In my case, it was unable to find the .eslintrc
file so I copied from node_modules/.bin to root.
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);
Use align-items: flex-start
on the container, or align-self: flex-start
on the flex items.
No need for display: inline-flex
.
An initial setting of a flex container is align-items: stretch
. This means that flex items will expand to cover the full length of the container along the cross axis.
The align-self
property does the same thing as align-items
, except that align-self
applies to flex items while align-items
applies to the flex container.
By default, align-self
inherits the value of align-items
.
Since your container is flex-direction: column
, the cross axis is horizontal, and align-items: stretch
is expanding the child element's width as much as it can.
You can override the default with align-items: flex-start
on the container (which is inherited by all flex items) or align-self: flex-start
on the item (which is confined to the single item).
Learn more about flex alignment along the cross axis here:
Learn more about flex alignment along the main axis here:
From strdup man:
The strdup()
function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1
. The returned pointer can be passed to free()
. A null pointer is returned if the new string cannot be created.
Set below code in RouteConfig.cs in App_Start folder
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}
IF still not working then do below steps
Second Way : You simple follow below steps,
1) Right click on your Project
2) Select Properties
3) Select Web option and then Select Specific Page (Controller/View) and then set your login page
Here, Account is my controller and Login is my action method (saved in Account Controller)
Please take a look attached screenshot.
I have a function and stored it in a service so i can use it all over my app:
Service:
app.service('SplitArrayService', function () {
return {
SplitArray: function (array, columns) {
if (array.length <= columns) {
return [array];
};
var rowsNum = Math.ceil(array.length / columns);
var rowsArray = new Array(rowsNum);
for (var i = 0; i < rowsNum; i++) {
var columnsArray = new Array(columns);
for (j = 0; j < columns; j++) {
var index = i * columns + j;
if (index < array.length) {
columnsArray[j] = array[index];
} else {
break;
}
}
rowsArray[i] = columnsArray;
}
return rowsArray;
}
}
});
Controller:
$scope.rows = SplitArrayService.SplitArray($scope.images, 3); //im splitting an array of images into 3 columns
Markup:
<div class="col-sm-12" ng-repeat="row in imageRows">
<div class="col-sm-4" ng-repeat="image in row">
<img class="img-responsive" ng-src="{{image.src}}">
</div>
</div>
Note that one difference between git remote --prune
and git fetch --prune
is being fixed, with commit 10a6cc8, by Tom Miller (tmiller
) (for git 1.9/2.0, Q1 2014):
When we have a remote-tracking branch named "
frotz/nitfol
" from a previous fetch, and the upstream now has a branch named "**frotz"**,fetch
would fail to remove "frotz/nitfol
" with a "git fetch --prune
" from the upstream.
git would inform the user to use "git remote prune
" to fix the problem.
So: when a upstream repo has a branch ("frotz") with the same name as a branch hierarchy ("frotz/xxx", a possible branch naming convention), git remote --prune
was succeeding (in cleaning up the remote tracking branch from your repo), but git fetch --prune
was failing.
Not anymore:
Change the way "
fetch --prune
" works by moving the pruning operation before the fetching operation.
This way, instead of warning the user of a conflict, it automatically fixes it.
Using your example where...
countries= [nan, 'USA', 'UK', 'France']
Since nan is not equal to nan (nan != nan) and countries[0] = nan, you should observe the following:
countries[0] == countries[0]
False
However,
countries[1] == countries[1]
True
countries[2] == countries[2]
True
countries[3] == countries[3]
True
Therefore, the following should work:
cleanedList = [x for x in countries if x == x]
I implore everyone to use Mongoose's query builder language and promises instead of callbacks:
User.find().or([{ name: param }, { nickname: param }])
.then(users => { /*logic here*/ })
.catch(error => { /*error logic here*/ })
Read more about Mongoose Queries.
The Solution to this problem, tends to differ slightly from case to case.
The general way to solve it is to
1.) right-click the bootstrap pill and select inspect or inspect element if firefox
2.) copy the css selector for the rule that changes the color
3.) modify it in your custom css file like so...
.TheCssSelectorYouJustCopied{
background-color: #ff0000!important;//or any other color
}
Putting this question in the context of NIO and NIO.2 in java 7, async IO is one step more advanced than non-blocking.
With java NIO non-blocking calls, one would set all channels (SocketChannel, ServerSocketChannel, FileChannel, etc) as such by calling AbstractSelectableChannel.configureBlocking(false)
.
After those IO calls return, however, you will likely still need to control the checks such as if and when to read/write again, etc.
For instance,
while (!isDataEnough()) {
socketchannel.read(inputBuffer);
// do something else and then read again
}
With the asynchronous api in java 7, these controls can be made in more versatile ways.
One of the 2 ways is to use CompletionHandler
. Notice that both read
calls are non-blocking.
asyncsocket.read(inputBuffer, 60, TimeUnit.SECONDS /* 60 secs for timeout */,
new CompletionHandler<Integer, Object>() {
public void completed(Integer result, Object attachment) {...}
public void failed(Throwable e, Object attachment) {...}
}
}
Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.
Just use the setCookie and getCookie methods mentioned there.
So, the code will look something like:
<script>
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function cssSelected() {
var cssSelected = $('#myList')[0].value;
if (cssSelected !== "select") {
setCookie("selectedCSS", cssSelected, 3);
}
}
$(document).ready(function() {
$('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
<option value="select">--Select--</option>
<option value="style-1.css">CSS1</option>
<option value="style-2.css">CSS2</option>
<option value="style-3.css">CSS3</option>
<option value="style-4.css">CSS4</option>
</select>