In [1]: import sys
In [2]: sys.version
2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec 6 2015, 18:08:32)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
In [3]: sys.version_info
sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)
In [4]: sys.version_info >= (2,7)
Out[4]: True
In [5]: sys.version_info >= (3,)
Out[5]: False
For my Raspberry Pi 3B model it was
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface wlan1 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
Ctrl + Shift + P Duplicate Workspace in New Window Enter
from: https://code.visualstudio.com/updates/v1_24#_duplicate-workspace-in-new-window
Swift 5: In the main view controller, or main navigation controller if you have,
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override var prefersStatusBarHidden: Bool {
return false
}
And "View controller-based status bar appearance" in plist must be YES, otherwise the above code will not be called.
If you want to hide status bar when launching app, "Status bar is initially hidden" in plist must be YES. This can prevent launch image from being distorted when extra blue bar showing on screen top.
You can use <i [className]="'fa fa-' + data?.icon"> </i>
XMLSpy does that for you, although that's not free...
I believe that Liquid Xml Studio does it for you and is free, but I have not personally used it to create test data.
input.split(/\s*[\s,]\s*/)
… \s*
matches zero or more white space characters (not just spaces, but also tabs and newlines).
... [\s,]
matches one white space character or one comma
If you want to avoid blank elements from input like "foo,bar,,foobar"
, this will do the trick:
input.split(/(\s*,?\s*)+/)
The +
matches one or more of the preceding character or group.
Edit:
Added ?
after comma which matches zero or one comma.
Edit 2:
Turns out edit 1 was a mistake. Fixed it. Now there has to be at least one comma or one space for the expression to find a match.
It is a server error, not a client error. If server errors weren't to be returned to the client, there wouldn't have been created an entire status code class for them (i.e. 5xx).
You can't hide the fact that you either made a programming error or some service you rely on is unavailable, and that certainly isn't the client's fault. Returning any other range of code in those cases than the 5xx series would make no sense.
RFC 7231 mentions in section 6.6. Server Error 5xx:
The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method.
This is exactly the case. There's nothing "internal" about the code "500 Internal Server Error" in the sense that it shouldn't be exposed to the client.
Begining with Python 3, all strings are unicode objects.
a = 'Happy New Year' # Python 3
b = unicode('Happy New Year') # Python 2
The instructions above are the same. So I think you should remove the .decode('utf-8')
part because you already have a unicode object.
I felt like replying as well, explaining the same thing as the others a bit differently. I am sure you know most of this, but it might help someone else.
<a href="#" class="view">
The
href="#"
part is a commonly used way to make sure the link doesn't lead anywhere on it's own. the #-attribute is used to create a link to some other section in the same document. For example clicking a link of this kind:
<a href="#news">Go to news</a>
will take you to wherever you have the
<a name="news"></a>
code. So if you specify # without any name like in your case, the link leads nowhere.
The
class="view"
part gives it an identifier that CSS or javascript can use. Inside the CSS-files (if you have any) you will find specific styling procedures on all the elements tagged with the "view"-class.
To find out where the URL is specified I would look in the javascript code. It is either written directly in the same document or included from another file.
Search your source code for something like:
<script type="text/javascript"> bla bla bla </script>
or
<script> bla bla bla </script>
and then search for any reference to your "view"-class. An included javascript file can look something like this:
<script type="text/javascript" src="include/javascript.js"></script>
In that case, open javascript.js under the "include" folder and search in that file. Most commonly the includes are placed between <head>
and </head>
or close to the </body>
-tag.
A faster way to find the link is to search for the actual link it goes to. For example, if you are directed to http://www.google.com/search?q=html when you click it, search for "google.com" or something in all the files you have in your web project, just remember the included files.
In many text editors you can open all the files at once, and then search in them all for something.
Add display: block;
and overflow: auto;
to .my-table
. This will simply cut off anything past the 280px
limit you enforced. There's no way to make it "look pretty" with that requirement due to words like pélagosthrough
which are wider than 280px
.
strace lists all system calls done by the process it's applied to. If you don't know what system calls mean, you won't be able to get much mileage from it.
Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is actually attempting to do, as distinct from what you expected it to.
You can achieve with following way
this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
There are two general techniques that I would recommend for this in C++11 and above, one for compile time dimensions and one for run time. Both answers assume you want uniform, two-dimensional arrays (not jagged ones).
Use a std::array
of std::array
and then use new
to put it on the heap:
// the alias helps cut down on the noise:
using grid = std::array<std::array<int, sizeX>, sizeY>;
grid * ary = new grid;
Again, this only works if the sizes of the dimensions are known at compile time.
The best way to accomplish a 2 dimensional array with sizes only known at runtime is to wrap it into a class. The class will allocate a 1d array and then overload operator []
to provide indexing for the first dimension.
This works because in C++ a 2D array is row-major:
(Taken from http://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/)
A contiguous sequence of memory is good for performance reasons and is also easy to clean up. Here's an example class that omits a lot of useful methods but shows the basic idea:
#include <memory>
class Grid {
size_t _rows;
size_t _columns;
std::unique_ptr<int[]> data;
public:
Grid(size_t rows, size_t columns)
: _rows{rows},
_columns{columns},
data{std::make_unique<int[]>(rows * columns)} {}
size_t rows() const { return _rows; }
size_t columns() const { return _columns; }
int *operator[](size_t row) { return row * _columns + data.get(); }
int &operator()(size_t row, size_t column) {
return data[row * _columns + column];
}
}
So we create an array with std::make_unique<int[]>(rows * columns)
entries. We overload operator []
which will index the row for us. It returns an int *
which points to the beginning of the row, which can then be dereferenced as normal for the column. Note that make_unique
first ships in C++14 but you can polyfill it in C++11 if necessary.
It's also common for these types of structures to overload operator()
as well:
int &operator()(size_t row, size_t column) {
return data[row * _columns + column];
}
Technically I haven't used new
here, but it's trivial to move from std::unique_ptr<int[]>
to int *
and use new
/delete
.
No, there is no such printf width specifier to print floating-point with maximum precision. Let me explain why.
The maximum precision of float
and double
is variable, and dependent on the actual value of the float
or double
.
Recall float
and double
are stored in sign.exponent.mantissa format. This means that there are many more bits used for the fractional component for small numbers than for big numbers.
For example, float
can easily distinguish between 0.0 and 0.1.
float r = 0;
printf( "%.6f\n", r ) ; // 0.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // 0.100000
But float
has no idea of the difference between 1e27
and 1e27 + 0.1
.
r = 1e27;
printf( "%.6f\n", r ) ; // 999999988484154753734934528.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // still 999999988484154753734934528.000000
This is because all the precision (which is limited by the number of mantissa bits) is used up for the large part of the number, left of the decimal.
The %.f
modifier just says how many decimal values you want to print from the float number as far as formatting goes. The fact that the accuracy available depends on the size of the number is up to you as the programmer to handle. printf
can't/doesn't handle that for you.
Do you want to do it automatically or manually? If manually, a JAR file is really just a ZIP file, so you should be able to open it with any ZIP reader. (You may need to change the extension first.) If you want to update the JAR file automatically via Eclipse, you may want to look into Ant support in Eclipse and look at the zip task.
You can use the time()
method of datetime
objects to get the time of day, which you can use for comparison without taking the date into account:
>>> this_morning = datetime.datetime(2009, 12, 2, 9, 30)
>>> last_night = datetime.datetime(2009, 12, 1, 20, 0)
>>> this_morning.time() < last_night.time()
True
A simple solution for me was to go to Properties -> Java Build Path -> Order and Export, then check the Apache Tomcat library. This is assumes you've already set Tomcat as your deployment target and are still getting the error.
View the Inner Exception of the exception to get a more specific error message.
One way to view the Inner Exception would be to catch the exception, and put a breakpoint on it. Then in the Locals window: select the Exception variable > InnerException > Message
And/Or just write to console:
catch (Exception e)
{
Console.WriteLine(e.InnerException.Message);
}
Should a dictionary like:
{'red': '0.500', 'yellow': '0.250, 'blue': '0.125'}
be required out of a dataframe like:
a b
0 red 0.500
1 yellow 0.250
2 blue 0.125
simplest way would be to do:
dict(df.values)
working snippet below:
import pandas as pd
df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
dict(df.values)
If this is your own collection class rather than a built in one, you need to override its toString method. Eclipse calls that function for any objects for which it does not have a hard-wired formatting.
If by Alt-F4 or X you mean "Exit the Application Immediately Without Regard for What Other Windows or Threads are Running", then System.exit(...)
will do exactly what you want in a very abrupt, brute-force, and possibly problematic fashion.
If by Alt-F4 or X you mean hide the window, then frame.setVisible(false)
is how you "close" the window. The window will continue to consume resources/memory but can be made visible again very quickly.
If by Alt-F4 or X you mean hide the window and dispose of any resources it is consuming, then frame.dispose()
is how you "close" the window. If the frame was the last visible window and there are no other non-daemon threads running, the program will exit. If you show the window again, it will have to reinitialize all of the native resources again (graphics buffer, window handles, etc).
dispose()
might be closest to the behavior that you really want. If your app has multiple windows open, do you want Alt-F4 or X to quit the app or just close the active window?
The Java Swing Tutorial on Window Listeners may help clarify things for you.
select to_number(exception_value) from exception where to_number(exception_value) = 105
Some of the best practices regarding observables unsubscriptions inside Angular components:
A quote from Routing & Navigation
When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.
There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions.
The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.
Feel free to unsubscribe anyway. It is harmless and never a bad practice.
And in responding to the following links:
http
observableI collected some of the best practices regarding observables unsubscriptions inside Angular components to share with you:
http
observable unsubscription is conditional and we should consider the effects of the 'subscribe callback' being run after the component is destroyed on a case by case basis. We know that angular unsubscribes and cleans the http
observable itself (1), (2). While this is true from the perspective of resources it only tells half the story. Let's say we're talking about directly calling http
from within a component, and the http
response took longer than needed so the user closed the component. The subscribe()
handler will still be called even if the component is closed and destroyed. This can have unwanted side effects and in the worse scenarios leave the application state broken. It can also cause exceptions if the code in the callback tries to call something that has just been disposed of. However at the same time occasionally they are desired. Like, let's say you're creating an email client and you trigger a sound when the email is done sending - well you'd still want that to occur even if the component is closed (8).AsyncPipe
as much as possible because it automatically unsubscribes from the observable on component destruction.ActivatedRoute
observables like route.params
if they are subscribed inside a nested (Added inside tpl with the component selector) or dynamic component as they may be subscribed many times as long as the parent/host component exists. No need to unsubscribe from them in other scenarios as mentioned in the quote above from Routing & Navigation
docs.OnDestroy
lifecycle hook which will be called when the service is destroyed, according to the docs.takeUntil
(3) or you can use this npm
package mentioned at (4) The easiest way to unsubscribe from Observables in Angular.FormGroup
observables like form.valueChanges
and form.statusChanges
Renderer2
service like renderer2.listen
HostListener
as angular cares well about removing the event listeners if needed and prevents any potential memory leak due to event bindings.A nice final tip: If you don't know if an observable is being automatically unsubscribed/completed or not, add a complete
callback to subscribe(...)
and check if it gets called when the component is destroyed.
SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp
you need to use a query like this:
select * from mytable where msisdn like '%7%'
or
select * from mytable where msisdn like '56655%'
The fastest way if your keys are in an SSH agent:
$ ssh-add -L | ssh-keygen -E md5 -lf /dev/stdin
Each key in the agent will be printed as:
4096 MD5:8f:c9:dc:40:ec:9e:dc:65:74:f7:20:c1:29:d1:e8:5a /Users/cmcginty/.ssh/id_rsa (RSA)
I just wanted to say that after trying a bunch of things, what fixed my CORS problem was simply using an older version of socket.io (version 2.2.0). My package.json file now looks like this:
{
"name": "current-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"devStart": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"socket.io": "^2.2.0"
},
"devDependencies": {
"nodemon": "^1.19.0"
}
}
If you execute npm install
with this, you may find that the CORS problem goes away when trying to use socket.io. At least it worked for me.
I know that this already has been answered but.....
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="1000"
android:repeatCount="infinite"
android:repeatMode="reverse"
/>
Quick and easy way to quickly do a fade in and out with a self repeat. Enjoy
EDIT : In your activity add this:
yourView.startAnimation(AnimationUtils.loadAnimation(co??ntext, R.anim.yourAnimation));
Only this is necessary
session_start();
unset($_SESSION["nome"]); // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");
If this is being done for scrolling to the bottom of chat window, do the following
The idea of scrolling to a particular div in the chat was the following
1) Each chat div consisting of Person, time and message is run in a for loop with class chatContentbox
2) querySelectorAll finds all such arrays. It could be 400 nodes (400 chats)
3) go to the last one
4) scrollIntoView()
let lastChatBox = document.querySelectorAll('.chatContentBox');
lastChatBox = lastChatBox[lastChatBox.length-1];
lastChatBox.scrollIntoView();
Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.
To enable it follow these steps:
Working from J.F. Sebastian's answer, and several other sources, I've put together a simple subprocess manager. It provides the request non-blocking reading, as well as running several processes in parallel. It doesn't use any OS-specific call (that I'm aware) and thus should work anywhere.
It's available from pypi, so just pip install shelljob
. Refer to the project page for examples and full docs.
With "Please select one Item"
@Html.DropDownListFor(model => model.ContentManagement_Send_Section,
new List<SelectListItem> { new SelectListItem { Value = "0", Text = "Plese Select one Item" } }
.Concat(db.NameOfPaperSections.Select(x => new SelectListItem { Text = x.NameOfPaperSection, Value = x.PaperSectionID.ToString() })),
new { @class = "myselect" })
Derived from the codes: Master Programmer && Joel Wahlund ;
King Reference : https://stackoverflow.com/a/1528193/1395101 JaredPar ;
Thanks Master Programmer && Joel Wahlund && JaredPar ;
Good luck friends.
Create a python dictionary to return as the response:
response = {'key': 'value'}
Then you can use json.dumps() or flask.jsonify() to turn a python dictionary into JSON:
from json import dumps
return dumps(response)
from flask import jsonify
return jsonify(response)
Note that flask.jsonify() is made for flask and also it has some more advatages. You can use it like in the following code:
from flask import jsonify
params = {
'key': 'value'
}
return jsonify(**params)
This is like using the following line:
return jsonify(key='value')
Remeber in this code you don't need the response dictionary!
Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:
If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.
In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.
AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.
If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.
Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
You can follow this approach:
void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
int val;
if (dic.TryGetValue(key, out val))
{
// yay, value exists!
dic[key] = val + newValue;
}
else
{
// darn, lets add the value
dic.Add(key, newValue);
}
}
The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary.
If you use ContainsKey
to check the existance and update the value using dic[key] = val + newValue;
then you are accessing the dictionary twice.
Easy in MySQL:
UPDATE users AS U1, users AS U2
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id
You can do it right in your XML file:
android:onClick="@drawable/ic_action_search"
Use awk
with a flag to trigger the print when necessary:
$ awk '/abc/{flag=1;next}/mno/{flag=0}flag' file
def1
ghi1
jkl1
def2
ghi2
jkl2
How does this work?
/abc/
matches lines having this text, as well as /mno/
does. /abc/{flag=1;next}
sets the flag
when the text abc
is found. Then, it skips the line. /mno/{flag=0}
unsets the flag
when the text mno
is found.flag
is a pattern with the default action, which is to print $0
: if flag
is equal 1 the line is printed.For a more detailed description and examples, together with cases when the patterns are either shown or not, see How to select lines between two patterns?.
If conditions is the best way to do it. If u want the count use pivot table of buckets. It's the easiest way and the if conditions can go for more than 5-6 buckets too
To click Ctrl+A, you can do it with Actions
Actions action = new Actions();
action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0061')).perform();
\u0061 represents the character 'a'
\u0041 represents the character 'A'
To press other characters refer the unicode character table - http://unicode.org/charts/PDF/U0000.pdf
Use a custom Listview.
You can also customize how row looks by having a custom background. activity_main.xml
<?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"
android:background="#0095FF"> //background color
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="@android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
MainActivity
Define populateString() in MainActivity
public class MainActivity extends Activity {
String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data_array = populateString();
ListView ll = (ListView) findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter();
ll.setAdapter(cus);
}
class CustomAdapter extends BaseAdapter
{
LayoutInflater mInflater;
public CustomAdapter()
{
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data_array.length;//listview item count.
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder vh;
vh= new ViewHolder();
if(convertView==null )
{
convertView=mInflater.inflate(R.layout.row, parent,false);
//inflate custom layour
vh.tv2= (TextView)convertView.findViewById(R.id.textView2);
}
else
{
convertView.setTag(vh);
}
//vh.tv2.setText("Position = "+position);
vh.tv2.setText(data_array[position]);
//set text of second textview based on position
return convertView;
}
class ViewHolder
{
TextView tv1,tv2;
}
}
}
row.xml. Custom layout for each row.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Header" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TextView" />
</LinearLayout>
Inflate a custom layout. Use a view holder for smooth scrolling and performance.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about listview performance by android developers.
You could also use chpasswd:
echo username:new_password | chpasswd
so, you change password for user username
to new_password
.
I've found this page on their github repo, I'll just paste the content here.
There are two main approaches for serializing and restoring a model.
The first (recommended) saves and loads only the model parameters:
torch.save(the_model.state_dict(), PATH)
Then later:
the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))
The second saves and loads the entire model:
torch.save(the_model, PATH)
Then later:
the_model = torch.load(PATH)
However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.
This is the best way to do it, very simple.
$msg = "Hello this is a string";
$first_index_of_i = stripos($msg,'i');
$last_index_of_i = strripos($msg, 'i');
echo "First i : " . $first_index_of_i . PHP_EOL ."Last i : " . $last_index_of_i;
Most of the IDE you can configure the default mask for some kind of data as date, currency, decimal separator, etc.
If your are using Oracle SQL Developer:
Tool > Preferences > Database > NLS
Date Format: YYYY-MM-DD HH24:MI:SS
If you want to exit from a simple if else
statement but still stays within a particular context (not by returning to the calling context), you can just set the block condition to false:
if(condition){
//do stuff
if(something happens)
condition = false;
}
This will guarantee that there is no further execution, the way I think you want it..You can only use break in a loop
or switch case
Google changed how much crash reports you actually get. Previously you only got manual reported bug reports.
Since the last developer conference and the introducation of Android Vitals you also get crash reports from users which have enabled to share diagnostics data.
You'll see all crashes collected from Android devices whose users have opted in to automatically share usage and diagnostics data. Data is available for the previous two months.
// here is how you can detect dragging in all four directions
var isDragging = false;
$("some DOM element").mousedown(function(e) {
var previous_x_position = e.pageX;
var previous_y_position = e.pageY;
$(window).mousemove(function(event) {
isDragging = true;
var x_position = event.pageX;
var y_position = event.pageY;
if (previous_x_position < x_position) {
alert('moving right');
} else {
alert('moving left');
}
if (previous_y_position < y_position) {
alert('moving down');
} else {
alert('moving up');
}
$(window).unbind("mousemove");
});
}).mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
$(window).unbind("mousemove");
});
In my case, I need both JDK 8 (trying to use the AVD and SDK manager in Qt under ubuntu) and 11 for different tools. Removing version 11 is not an option.
The 'JAVA_OPTS' solutions did not do anything. I don't really like the export JAVA_HOME, as it might force you do launch whatever tool calls these utils from the same shell (like Qt), or force you to make this permanent, which is not convenient.
So for me the solution is quite simple. Add something like this in the second line of ~/Android/tools/bin/sdkmanager and ~/Android/tools/bin/avdmanager:
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"
(or whatever the path is to your rev 8 jdk).
With this, these command line tools work in a stand alone mode, they work also when called by other tools such as Qt, and jdk 11 is still the system default for others. No need to mix libs etc...
The only downside is that any update to these command line tools will erase these modifications, which you will have to put back in.
Simple. On your code first, set the type of DateTime to DateTime?. So you can work with nullable DateTime type in database. Entity example:
public class Alarme
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? DataDisparado { get; set; }//.This allow you to work with nullable datetime in database.
public DateTime? DataResolvido { get; set; }//.This allow you to work with nullable datetime in database.
public long Latencia { get; set; }
public bool Resolvido { get; set; }
public int SensorId { get; set; }
[ForeignKey("SensorId")]
public virtual Sensor Sensor { get; set; }
}
Transfer is entirely server-side. Client address bar stays constant. Some complexity about the transfer of context between requests. Flushing and restarting page handlers can be expensive so do your transfer early in the pipeline e.g. in an HttpModule during BeginRequest. Read the MSDN docs carefully, and test and understand the new values of HttpContext.Request - especially in Postback scenarios. We usually use Server.Transfer for error scenarios.
Redirect terminates the request with a 302 status and client-side roundtrip response with and internally eats an exception (minor server perf hit - depends how many you do a day) Client then navigates to new address. Browser address bar & history updates etc. Client pays the cost of an extra roundtrip - cost varies depending on latency. In our business we redirect a lot we wrote our own module to avoid the exception cost.
Here is some code:
private void dgvStandingOrder_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvStandingOrder.Columns[e.ColumnIndex].Name == "IsSelected" && dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
{
bool isChecked = (bool)dgvStandingOrder[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
if (isChecked == false)
{
dgvStandingOrder.Rows[e.RowIndex].Cells["Status"].Value = "";
}
dgvStandingOrder.EndEdit();
}
}
private void dgvStandingOrder_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dgvStandingOrder_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
{
dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Use the method "toArray()"
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
Object[] mStringArray = mStringList.toArray();
for(int i = 0; i < mStringArray.length ; i++){
Log.d("string is",(String)mStringArray[i]);
}
or you can do it like this: (mentioned in other answers)
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);
for(int i = 0; i < mStringArray.length ; i++){
Log.d("string is",(String)mStringArray[i]);
}
http://developer.android.com/reference/java/util/ArrayList.html#toArray()
Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.
I think your answer is fine (and it's OK to accept it if you like). This is just "extra".
import numpy as np
a = np.arange(4,10).reshape(2,3)
wh = np.where(a>7)
gt = a>7
x = np.where(gt)
print "wh: ", wh
print "gt: ", gt
print "x: ", x
gives:
wh: (array([1, 1]), array([1, 2]))
gt: [[False False False]
[False True True]]
x: (array([1, 1]), array([1, 2]))
... but:
print "a[wh]: ", a[wh]
print "a[gt] ", a[gt]
print "a[x]: ", a[x]
gives:
a[wh]: [8 9]
a[gt] [8 9]
a[x]: [8 9]
You can make you request headers by yourself using:
// open a socket connection on port 80
$fp = fsockopen($host, 80);
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
// close the socket connection:
fclose($fp);
Like writen on how make request
You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.
To run code after the page has finished loading, use the $(document).ready callback:
$(document).ready(function(){
$('#some-id').trigger('click');
});
My gut told me the same thing when I came across this design.
I am working on a code base where there are three dbContexts to one database. 2 out of the 3 dbcontexts are dependent on information from 1 dbcontext because it serves up the administrative data. This design has placed constraints on how you can query your data. I ran into this problem where you cannot join across dbcontexts. Instead what you are required to do is query the two separate dbcontexts then do a join in memory or iterate through both to get the combination of the two as a result set. The problem with that is instead of querying for a specific result set you are now loading all your records into memory and then doing a join against the two result sets in memory. It can really slow things down.
I would ask the question "just because you can, should you?"
See this article for the problem I came across related to this design.
The specified LINQ expression contains references to queries that are associated with different contexts
Unique key allows max 2 NULL values. Explaination:
create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)
insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')
select * from teppp
null string , address1
NULL,address2
NULL,address3
If you try inserting same values as below:
insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')
Every time you will get error like:
Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.
To be able to run options like --stacktrace
within a gradle command, you need to put it at the beginning, like:
./gradlew --stacktrace assembleMyBuild
E.g,
./gradlew --stacktrace assembleDebug
Internet options-->General Tab-->browsing History section.... click settings and then click "View objects". A list of your active X add on's are displayed in the windows folder that they are stored in. You can manipulate these files as you would any others. Simply delete the ones you want to uninstall and restart IE.
I am developer of SSMSBoost add-in that was recently released for SSMS2008/R2, the intention was to add add features that speed up daily routine tasks:
Shorcuts: F2 - (in SQL Editor): script object located unted cursor
CTRL + F2 - (in SQL Editor): find object located under cursor in object explorer and focus it +It includes Shortcut editor, that is missing in SSMS2008 (is coming in SSMS2012)
also SSMSBoost adds toolbar with buttons:
select * from
and you can also add your own token-replacement pairsThis looks like a situation for producer-consumer pattern. If you’re using java 5 or up, you may consider using blocking queue(java.util.concurrent.BlockingQueue) and leave the thread coordination work to the underlying framework/api implementation. See the example from java 5: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html or java 7 (same example): http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
These alternative libraries worked for me:
sudo apt-get update
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
In this way we can make it use the values to the pass the information between the controller to other page with TEMP DATA
I have made a function for that, you only call it in a batch program within needing to code more.
The working is basically the same as the others, as it's the best way to do it.
Here's the link where I have that function
Try this code with a Turkish currency compliant JavaScript
function dene() {
var inpt = document.getElementById("tar1").value;
var spt = inpt.split('');
spt.reverse();
var tek = ["", "Bir", "Iki", "Üç", "Dört", "Bes", "Alti", "Yedi", "Sekiz", "Dokuz"];
var onlu = ["", "On", "Yirmi", "Otuz", "Kirk", "Elli", "Atmis", "Yetmis", "Seksen", "Doksan"];
var Yuz = ["", "Yüz", "IkiYüz", "Üçyüz", "DörtYüz", "BesYüz", "AltiYüz", "YediYüz", "SekizYüz", "DokuzYüz"];
var ska = ["", "", "", "", "Bin", "Milyon", "Milyar", "Trilyon", "Katrilyon", "Kentilyon"];
var i, j;
var bas3 = "";
var bas6 = "";
var bas9 = "";
var bas12 = "";
var total;
for(i = 0; i < 1; i++) {
bas3 += Yuz[spt[i+2]] + onlu[spt[i+1]] + tek[spt[i]];
bas6 += Yuz[spt[i+5]] + onlu[spt[i+4]] + tek[spt[i+3]] + ska[4];
bas9 += Yuz[spt[i+8]] + onlu[spt[i+7]] + tek[spt[i+6]] + ska[5];
bas12 += Yuz[spt[i+11]] + onlu[spt[i+10]] + tek[spt[i+9]] + ska[6];
if(inpt.length < 4) {
bas6 = '';
bas9 = '';
}
if(inpt.length > 6 && inpt.slice(5, 6) == 0) {
bas6 = bas6.replace(/Bin/g, '');
}
if(inpt.length < 7) {
bas9 = '';
}
if(inpt.length > 9 && inpt.slice(1,3) == 000){
bas9 = bas9.replace(/Milyon/g, '');
}
if(inpt.length < 10) {
bas12 = '';
}
}
total = bas12 + bas9 + bas6 + bas3;
total = total.replace(NaN, '');
total = total.replace(undefined, '');
document.getElementById('demo').innerHTML =
total;
}
Here is a code to get the child elements (In java):
String childTag = childElement.getTagName();
if(childTag.equals("html"))
{
return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath(".."));
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++)
{
WebElement childrenElement = childrenElements.get(i);
String childrenElementTag = childrenElement.getTagName();
if(childTag.equals(childrenElementTag))
{
count++;
}
}
try this:
ren "File 1-1" "File 1 - %date:/=-% %time::=-%"
I had the same problem while using Jupyter Notebook, no matter what I updated in Python 3, conda, I could not get in Jupyter:
import sklearn
print (sklearn.__version__)
0.17.1
to SHOW scikit-learn-0.18.1
Finally, I removed Anaconda3 and Jupyter Notebook and reinstalled fresh. I got it to work.
http://ukitech.blogspot.com/2017/02/sklearnmodelselection.html
You have to replace YourID and value="3" for your current ones.
$(document).ready(function() {_x000D_
$('#YourID option[value="3"]').attr("selected", "selected");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
<option value="1">A</option>_x000D_
<option value="2">B</option>_x000D_
<option value="3">C</option>_x000D_
<option value="4">D</option>_x000D_
</select>
_x000D_
and value="3" for your current ones.
$('#YourID option[value="3"]').attr("selected", "selected");
<select id="YourID" >
<option value="1">A </option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
One option would be to use a System.ComponenetModel.BindingList rather than a list.
This allows you to use it directly within a DataGridView. And unlike a normal System.Collections.Generic.List updates the DataGridView on changes.
Add in the generated migration after creating the column the following (example)
add_index :photographers, :email, :unique => true
A List<T>
is an IEnumerable<T>
, so actually, there's no need to 'convert' a List<T>
to an IEnumerable<T>
.
Since a List<T>
is an IEnumerable<T>
, you can simply assign a List<T>
to a variable of type IEnumerable<T>
.
The other way around, not every IEnumerable<T>
is a List<T>
offcourse, so then you'll have to call the ToList()
member method of the IEnumerable<T>
.
Thanks to @Jousby's solution, I managed to get mine working as well, but found I had to improve his solution's Bootstrap modal markup a bit to make it render correctly as demonstrated in the official examples.
So, here's my modified version of the generic confirm
function that worked fine:
/* Generic Confirm func */
function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {
var confirmModal =
$('<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<a class="close" data-dismiss="modal" >×</a>' +
'<h3>' + heading +'</h3>' +
'</div>' +
'<div class="modal-body">' +
'<p>' + question + '</p>' +
'</div>' +
'<div class="modal-footer">' +
'<a href="#!" class="btn" data-dismiss="modal">' +
cancelButtonTxt +
'</a>' +
'<a href="#!" id="okButton" class="btn btn-primary">' +
okButtonTxt +
'</a>' +
'</div>' +
'</div>' +
'</div>' +
'</div>');
confirmModal.find('#okButton').click(function(event) {
callback();
confirmModal.modal('hide');
});
confirmModal.modal('show');
};
/* END Generic Confirm func */
Quite simply, that string is not valid JSON. As the error says, JSON documents need to use double quotes.
You need to fix the source of the data.
According to OpenCV cheat-sheet this can be done as follows:
IplImage* oldC0 = cvCreateImage(cvSize(320,240),16,1);
Mat newC = cvarrToMat(oldC0);
The cv::cvarrToMat function takes care of the conversion issues.
Just an update.
If the ticked answer is working fine for you but it shows nothing when the search text is empty. Here is the solution:
private class ItemFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
if(constraint.length() == 0)
{
results.count = originalData.size();
results.values = originalData;
}else {
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
For any query comment below
var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');
To loop with each()
$("a.directions-link").each(function() {
var $this = $(this);
var _href = $this.attr("href");
$this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});
From Python version 2.6 on you can use multiple arguments to set.intersection()
, like
u = set.intersection(s1, s2, s3)
If the sets are in a list, this translates to:
u = set.intersection(*setlist)
where *a_list
is list expansion
Note that set.intersection
is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.
Based on this answer from @Guilherme Ferreira you can trigger the parseFloat
method every time the field changes. Therefore the value always shows two decimal places, even if a user changes the value by manual typing a number.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function () {_x000D_
$(".floatNumberField").change(function() {_x000D_
$(this).val(parseFloat($(this).val()).toFixed(2));_x000D_
});_x000D_
});_x000D_
</script>_x000D_
_x000D_
<input type="number" class="floatNumberField" value="0.00" placeholder="0.00" step="0.01" />
_x000D_
Try one of:
var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;
clientHeight
includes the height and vertical padding.
offsetHeight
includes the height, vertical padding, and vertical borders.
scrollHeight
includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.
With the following extension method you can get away without reflection:
public static Type GetListType<T>(this List<T> _)
{
return typeof(T);
}
Or more general:
public static Type GetEnumeratedType<T>(this IEnumerable<T> _)
{
return typeof(T);
}
Usage:
List<string> list = new List<string> { "a", "b", "c" };
IEnumerable<string> strings = list;
IEnumerable<object> objects = list;
Type listType = list.GetListType(); // string
Type stringsType = strings.GetEnumeratedType(); // string
Type objectsType = objects.GetEnumeratedType(); // BEWARE: object
Though I am late to this post, just updating my findings. This answer is only for Mac OS X.
$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern
In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.
$ sed 's/new/\
> /g' m1.json > m2.json
Worked! (in Mac OS X 10.9.3)
"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted
Well the easiest way that I do it is by typing the following into the .m file.
- (BOOL) prefersStatusBarHidden
{
return YES;
}
This should work!
If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue
: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)
ObjectMapper mapper = new ObjectMapper();
JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
JsonNode tree = jsonParser.readValueAsTree();
// Do stuff to the tree
mapper.readValue(tree, Foo.class);
You need to put your code into ngOnInit
and use the this
keyword:
ngOnInit() {
this.booksByStoreID = this.books.filter(
book => book.store_id === this.store.id);
}
You need ngOnInit
because the input store
wouldn't be set into the constructor:
ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)
In your code, the books filtering is directly defined into the class content...
Pretty sad, eh? The way I usually do it is build up a container of iterators instead of deleting during traversal. Then loop through the container and use map.erase()
std::map<K,V> map;
std::list< std::map<K,V>::iterator > iteratorList;
for(auto i : map ){
if ( needs_removing(i)){
iteratorList.push_back(i);
}
}
for(auto i : iteratorList){
map.erase(*i)
}
Add your php folder path to the System PATH and everything should work fine. It will also fix some other extensions that are broken.
You may need to check who the actual owner of the stored procedure is. If it is a specific different user then that could be why you can't access it.
Have you tried this ?
<input type="submit" style="visibility: hidden;" />
Since most browsers understand visibility:hidden
and it doesn't really work like display:none
, I'm guessing that it should be fine, though. Haven't really tested it myself, so CMIIW.
If you are looking to break through the 2^32 barrier then try this method:
/// <summary>
/// Generate a BigInteger given a Guid. Returns a number from 0 to 2^128
/// 0 to 340,282,366,920,938,463,463,374,607,431,768,211,456
/// </summary>
public BigInteger GuidToBigInteger(Guid guid)
{
BigInteger l_retval = 0;
byte[] ba = guid.ToByteArray();
int i = ba.Count();
foreach (byte b in ba)
{
l_retval += b * BigInteger.Pow(256, --i);
}
return l_retval;
}
The universe will decay to a cold and dark expanse before you experience a collision.
Oneliner:
array = [] << 1 << 2 << 3 #this is for fixnums.
or
a = %w| 1 2 3 4 5 |
or
a = [*'1'..'3']
or
a = Array.new(3, '1')
or
a = Array[*'1'..'3']
I had the same problem with Angular CLI: 10.1.5 The code works fine, but the error was shown in the VScode v1.50
Resolved by killing the terminal (ng serve) and restarting VScode.
in a bash script the following works:
#!/bin/sh
text="this is line one\nthis is line two\nthis is line three"
echo -e $text > filename
alternatively:
text="this is line one
this is line two
this is line three"
echo "$text" > filename
cat filename gives:
this is line one
this is line two
this is line three
Even this works.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
<item android:drawable="@android:color/white" />
</selector>
I added the android:drawable
attribute to each item, and their values are colors.
By the way, why do they say that color
is one of the attributes of selector
? They don't write that android:drawable
is required.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:color="hex_color"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>
Try this.. very easy to understand & implementation...
You can download sample code directly here https://github.com/Tech-Dev-Mobile/Json-Sample
- (void)simpleJsonParsingPostMetod
{
#warning set webservice url and parse POST method in JSON
//-- Temp Initialized variables
NSString *first_name;
NSString *image_name;
NSData *imageData;
//-- Convert string into URL
NSString *urlString = [NSString stringWithFormat:@"demo.com/your_server_db_name/service/link"];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//-- Append data into posr url using following method
NSMutableData *body = [NSMutableData data];
//-- For Sending text
//-- "firstname" is keyword form service
//-- "first_name" is the text which we have to send
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"firstname"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",first_name] dataUsingEncoding:NSUTF8StringEncoding]];
//-- For sending image into service if needed (send image as imagedata)
//-- "image_name" is file name of the image (we can set custom name)
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"%@\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//-- Sending data into server through URL
[request setHTTPBody:body];
//-- Getting response form server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Result = %@",result);
}
Adding this in the index.html
head worked for me:
<style>
html, body, #app, #app>div { position: absolute; width: 100% !important; height: 100% !important; }
</style>
As pointed in the comments, file
is a blob
:
file instanceof Blob; // true
And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader
Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');
function readFile(event) {
textarea.textContent = event.target.result;
console.log(event.target.result);
}
function changeFile() {
var file = input.files[0];
var reader = new FileReader();
reader.addEventListener('load', readFile);
reader.readAsText(file);
}
input.addEventListener('change', changeFile);
_x000D_
<input type="file">
<textarea rows="10" cols="50"></textarea>
_x000D_
This gets any foreign key that involves the chosen table. *Assumes a _FIRSTABLENAME_SECONDTABLENAME format.
declare @tablename as varchar(MAX)
SET @tablename = 'yourtablename'
SELECT name
FROM YOURDATABASE.sys.objects
WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' and (name LIKE '%_' + @tablename + 'empdb_%' or name LIKE '%_' + @tablename )
This is a more general form:
SELECT name
FROM YOURDATABASE_PROD.sys.objects
WHERE type_desc = 'FOREIGN_KEY_CONSTRAINT' and name LIKE '%' + @tablename + '%' and
name NOT LIKE '[a-zA-Z0-9]' + @tablename + '%' and name NOT LIKE '%' + @tablename + '[a-zA-Z0-9]'
Don't forget to add in app level gradle, apply plugin: 'kotlin-kapt'
You need to have file system permission to create the directory.
Example: In Ubuntu 10.04 apache (php) runs as user: www-data in group: www-data
Meaning the user www-data needs access to create the directory.
You can try this yourself by using: 'su www-data' to become the www-data user.
As a quick fix, you can do: sudo chmod 777 my_parent_dir
Try setting the core.autocrlf
configuration option to true
. Also have a look at the core.safecrlf
option.
Actually it sounds like core.safecrlf
might already be set in your repository, because (emphasis mine):
If this is not the case for the current setting of core.autocrlf, git will reject the file.
If this is the case, then you might want to check that your text editor is configured to use line endings consistently. You will likely run into problems if a text file contains a mixture of LF and CRLF line endings.
Finally, I feel that the recommendation to simply "use what you're given" and use LF terminated lines on Windows will cause more problems than it solves. Git has the above options to try to handle line endings in a sensible way, so it makes sense to use them.
Open the project's properties---> Java Build Path ---> Libraries tab ---> Add External Jars
will allow you to add jars.
You need to download commonsIO from here.
The code bellow allows the user to un-/check the checkboxes in the DataGridView, if the Cells are created in code
private void gvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)gvData.Rows[e.RowIndex].Cells[0];
if (chk.Value == chk.TrueValue)
{
gvData.Rows[e.RowIndex].Cells[0].Value = chk.FalseValue;
}
else
{
gvData.Rows[e.RowIndex].Cells[0].Value = chk.TrueValue;
}
}
For reading "plain" CSV files in Java, there is a library called OpenCSV, available here: http://opencsv.sourceforge.net/
There are 2 documents specifying the JSON format:
The accepted answer quotes from the 1st document. I think the 1st document is more clear, but the 2nd contains more detail.
The 2nd document says:
Objects
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.
So it is not forbidden to have a duplicate name, but it is discouraged.
1) The most simple way would be using WMPLib
WMPLib.WindowsMediaPlayer Player;
private void PlayFile(String url)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.PlayStateChange += Player_PlayStateChange;
Player.URL = url;
Player.controls.play();
}
private void Player_PlayStateChange(int NewState)
{
if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
{
//Actions on stop
}
}
2) Alternatively you can use the open source library NAudio. It can play mp3 files using different methods and actually offers much more than just playing a file.
This is as simple as
using NAudio;
using NAudio.Wave;
IWavePlayer waveOutDevice = new WaveOut();
AudioFileReader audioFileReader = new AudioFileReader("Hadouken! - Ugly.mp3");
waveOutDevice.Init(audioFileReader);
waveOutDevice.Play();
Don't forget to dispose after the stop
waveOutDevice.Stop();
audioFileReader.Dispose();
waveOutDevice.Dispose();
that is an error.
first of all, first line should be like this (be careful of capitals)
class Test(object):
Whenever you call a method of a class, it gets itself as the first argument (hence the name self) and method_two gives this error
>>> a.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
As stated in the JQuery documentation
The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
Yet another way of getting the last item from a MongoDB Collection (don't mind about the examples):
> db.collection.find().sort({'_id':-1}).limit(1)
Normal Projection
> db.Sports.find()
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
Sorted Projection ( _id: reverse order )
> db.Sports.find().sort({'_id':-1})
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }
sort({'_id':-1})
, defines a projection in descending order of all documents, based on their _id
s.
Sorted Projection ( _id: reverse order ): getting the latest (last) document from a collection.
> db.Sports.find().sort({'_id':-1}).limit(1)
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <
)
select *
from xxx
where dates >= '20121026'
and dates < '20121028'
If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.
select *
from xxx
where CAST(dates as DATE) between '20121026' and '20121027'
This explicitly tells SQL Server that you are only interested in the DATE portion of the dates
column for comparison against the BETWEEN range.
You can use an RDLC file provided in visual studio to define your report layout. You can view the rdlc using the ReportViewer control.
Both are provided out of the box with visual studio.
This will uninstall a gem installed by bundler:
bundle exec gem uninstall GEM_NAME
Note that this throws
ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>
but the gem is actually removed. Next time you run bundle install
the gem will be reinstalled.
var img = new Image();
img.onload = function(){
var height = img.height;
var width = img.width;
// code here to use the dimensions
}
img.src = url;
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'attrs.dynamic' , function(html){
element.html(scope.dynamic);
$compile(element.contents())(scope);
});
}
};
});
Try this element.html(scope.dynamic); than element.html(attr.dynamic);
I have come across this very useful article about async
and void
written by Jérôme Laban:
https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html
The bottom line is that an async+void
can crash the system and usually should be used only on the UI side event handlers.
The reason behind this is the Synchronization Context used by the AsyncVoidMethodBuilder, being none in this example. When there is no ambient Synchronization Context, any exception that is unhandled by the body of an async void method is rethrown on the ThreadPool. While there is seemingly no other logical place where that kind of unhandled exception could be thrown, the unfortunate effect is that the process is being terminated, because unhandled exceptions on the ThreadPool effectively terminate the process since .NET 2.0. You may intercept all unhandled exception using the AppDomain.UnhandledException event, but there is no way to recover the process from this event.
When writing UI event handlers, async void methods are somehow painless because exceptions are treated the same way found in non-async methods; they are thrown on the Dispatcher. There is a possibility to recover from such exceptions, with is more than correct for most cases. Outside of UI event handlers however, async void methods are somehow dangerous to use and may not that easy to find.
Templates need to be instantiated by the compiler before actually compiling them into object code. This instantiation can only be achieved if the template arguments are known. Now imagine a scenario where a template function is declared in a.h
, defined in a.cpp
and used in b.cpp
. When a.cpp
is compiled, it is not necessarily known that the upcoming compilation b.cpp
will require an instance of the template, let alone which specific instance would that be. For more header and source files, the situation can quickly get more complicated.
One can argue that compilers can be made smarter to "look ahead" for all uses of the template, but I'm sure that it wouldn't be difficult to create recursive or otherwise complicated scenarios. AFAIK, compilers don't do such look aheads. As Anton pointed out, some compilers support explicit export declarations of template instantiations, but not all compilers support it (yet?).
Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.
If @Region
is not a null
value (lets say @Region = 'South'
) it will not return rows where the Region field is null, regardless of the value of ANSI_NULLS.
ANSI_NULLS will only make a difference when the value of @Region
is null
, i.e. when your first query essentially becomes the second one.
In that case, ANSI_NULLS ON will not return any rows (because null = null
will yield an unknown boolean value (a.k.a. null
)) and ANSI_NULLS OFF will return any rows where the Region field is null (because null = null
will yield true
)
When you do b = a
you simply create another pointer to the same memory of a,
that's why when you append to b , a changes too.
You need to create copy of a and that's done like this:
b = a[:]
If you want one with a functional style, like this:
const table = document.getElementById("mytab1");
const cells = table.rows.toArray()
.flatMap(row => row.cells.toArray())
.map(cell => cell.innerHTML); //["col1 Val1", "col2 Val2", "col1 Val3", "col2 Val4"]
You may modify the prototype object of HTMLCollection (allowing to use in a way that resembles extension methods in C#) and embed into it a function that converts collection into array, allowing to use higher order funcions with the above style (kind of linq style in C#):
Object.defineProperty(HTMLCollection.prototype, "toArray", {
value: function toArray() {
return Array.prototype.slice.call(this, 0);
},
writable: true,
configurable: true
});
The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.
The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).
For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.
There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.
In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.
Example:
create table longtable(id number,text long);
insert into longtable values(1,'hello world');
insert into longtable values(2,'say hello!');
commit;
create or replace function search_long(r rowid) return varchar2 is
temporary_varchar varchar2(4000);
begin
select text into temporary_varchar from longtable where rowid=r;
return temporary_varchar;
end;
/
SQL> select text from longtable where search_long(rowid) like '%hello%';
TEXT
--------------------------------------------------------------------------------
hello world
say hello!
But be careful. A PL/SQL function will only search the first 32K of LONG.
You didn't call the function and you have other errors, should be:
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
You were setting inputVal
to the string value of the input, but then you tried to set style.backgroundColor
on it, which won't work because it's a string, not the element. I changed your variable to store the element object instead of its value.
You should make tags their own table with a linking table.
items:
id object
1 lamp
2 table
3 stool
4 bench
tags:
id tag
1 furniture
2 chair
items_tags:
item_id tag_id
1 1
2 1
3 1
4 1
3 2
4 2
for more classes adding
... className={`${classes.hello} ${classes.hello1}`...
If you want a simple way to preserve duplicates, you could use groupby
:
>>> ptest = pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id', 'value'])
>>> ptest
id value
0 a 1
1 a 2
2 b 3
>>> {k: g["value"].tolist() for k,g in ptest.groupby("id")}
{'a': [1, 2], 'b': [3]}
Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random()
.
Math.random()
Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.
I call this the "Fractional-Unique-ID".
Wrote code to generate 1,000,000 Math.random()
numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):
random_numbers = []
for (i = 0; i < 1000000; i++) {
random_numbers.push(Math.random());
//random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16
}
if (i === 1000000) {
console.log("Before checking duplicate");
console.log(random_numbers.length);
console.log("After checking duplicate");
random_set = new Set(random_numbers); // Set removes duplicates
console.log([...random_set].length); // length is still the same after removing
}
In my case I remembered that a hole in the firewall was created for this address some time ago, so I had to set useDefaultWebProxy="false" on the binding in the config file, as if the default was to use the proxy if useDefaultWebProxy is not specified.
Perhaps you could think about the problem in a different way. WebClient
and HttpClient
are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient
and HttpClient
, and then use the IoC container to inject the implementation via config.
What this would allow you to do would be to switch between HttpClient
and WebClient
easily so that you are able to objectively test in the production environment.
So questions like:
Will HttpClient be a better design choice if we upgrade to .Net 4.5?
Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient
or WebClient
.
/// <summary>
/// Dependency Injection abstraction for rest clients.
/// </summary>
public interface IClient
{
/// <summary>
/// Adapter for serialization/deserialization of http body data
/// </summary>
ISerializationAdapter SerializationAdapter { get; }
/// <summary>
/// Sends a strongly typed request to the server and waits for a strongly typed response
/// </summary>
/// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
/// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
/// <param name="request">The request that will be translated to a http request</param>
/// <returns></returns>
Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);
/// <summary>
/// Default headers to be sent with http requests
/// </summary>
IHeadersCollection DefaultRequestHeaders { get; }
/// <summary>
/// Default timeout for http requests
/// </summary>
TimeSpan Timeout { get; set; }
/// <summary>
/// Base Uri for the client. Any resources specified on requests will be relative to this.
/// </summary>
Uri BaseUri { get; set; }
/// <summary>
/// Name of the client
/// </summary>
string Name { get; }
}
public class Request<TRequestBody>
{
#region Public Properties
public IHeadersCollection Headers { get; }
public Uri Resource { get; set; }
public HttpRequestMethod HttpRequestMethod { get; set; }
public TRequestBody Body { get; set; }
public CancellationToken CancellationToken { get; set; }
public string CustomHttpRequestMethod { get; set; }
#endregion
public Request(Uri resource,
TRequestBody body,
IHeadersCollection headers,
HttpRequestMethod httpRequestMethod,
IClient client,
CancellationToken cancellationToken)
{
Body = body;
Headers = headers;
Resource = resource;
HttpRequestMethod = httpRequestMethod;
CancellationToken = cancellationToken;
if (Headers == null) Headers = new RequestHeadersCollection();
var defaultRequestHeaders = client?.DefaultRequestHeaders;
if (defaultRequestHeaders == null) return;
foreach (var kvp in defaultRequestHeaders)
{
Headers.Add(kvp);
}
}
}
public abstract class Response<TResponseBody> : Response
{
#region Public Properties
public virtual TResponseBody Body { get; }
#endregion
#region Constructors
/// <summary>
/// Only used for mocking or other inheritance
/// </summary>
protected Response() : base()
{
}
protected Response(
IHeadersCollection headersCollection,
int statusCode,
HttpRequestMethod httpRequestMethod,
byte[] responseData,
TResponseBody body,
Uri requestUri
) : base(
headersCollection,
statusCode,
httpRequestMethod,
responseData,
requestUri)
{
Body = body;
}
public static implicit operator TResponseBody(Response<TResponseBody> readResult)
{
return readResult.Body;
}
#endregion
}
public abstract class Response
{
#region Fields
private readonly byte[] _responseData;
#endregion
#region Public Properties
public virtual int StatusCode { get; }
public virtual IHeadersCollection Headers { get; }
public virtual HttpRequestMethod HttpRequestMethod { get; }
public abstract bool IsSuccess { get; }
public virtual Uri RequestUri { get; }
#endregion
#region Constructor
/// <summary>
/// Only used for mocking or other inheritance
/// </summary>
protected Response()
{
}
protected Response
(
IHeadersCollection headersCollection,
int statusCode,
HttpRequestMethod httpRequestMethod,
byte[] responseData,
Uri requestUri
)
{
StatusCode = statusCode;
Headers = headersCollection;
HttpRequestMethod = httpRequestMethod;
RequestUri = requestUri;
_responseData = responseData;
}
#endregion
#region Public Methods
public virtual byte[] GetResponseData()
{
return _responseData;
}
#endregion
}
You can use Task.Run
to make WebClient
run asynchronously in its implementation.
Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient
may work better for some customers, and HttpClient
may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.
BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.
The SqlDataReader
is a valid data source for the DataTable
. As such, all you need to do its this:
public DataTable GetData()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne]";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
return dt;
}
I'm using this function that find all images in my letter and attaches it to the message.
Parameters: Takes your HTML (which you want to send);
Return: The necessary HTML and headers, which you can use in mail()
;
Example usage:
define("DEFCALLBACKMAIL", "[email protected]"); // WIll be shown as "from".
$final_msg = preparehtmlmail($html); // give a function your html*
mail('[email protected]', 'your subject', $final_msg['multipart'], $final_msg['headers']);
// send email with all images from html attached to letter
function preparehtmlmail($html) {
preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
$i = 0;
$paths = array();
foreach ($matches[1] as $img) {
$img_old = $img;
if(strpos($img, "http://") == false) {
$uri = parse_url($img);
$paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
$content_id = md5($img);
$html = str_replace($img_old,'cid:'.$content_id,$html);
$paths[$i++]['cid'] = $content_id;
}
}
$boundary = "--".md5(uniqid(time()));
$headers .= "MIME-Version: 1.0\n";
$headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
$headers .= "From: ".DEFCALLBACKMAIL."\r\n";
$multipart = '';
$multipart .= "--$boundary\n";
$kod = 'utf-8';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
$multipart .= "$html\n\n";
foreach ($paths as $path) {
if(file_exists($path['path']))
$fp = fopen($path['path'],"r");
if (!$fp) {
return false;
}
$imagetype = substr(strrchr($path['path'], '.' ),1);
$file = fread($fp, filesize($path['path']));
fclose($fp);
$message_part = "";
switch ($imagetype) {
case 'png':
case 'PNG':
$message_part .= "Content-Type: image/png";
break;
case 'jpg':
case 'jpeg':
case 'JPG':
case 'JPEG':
$message_part .= "Content-Type: image/jpeg";
break;
case 'gif':
case 'GIF':
$message_part .= "Content-Type: image/gif";
break;
}
$message_part .= "; file_name = \"$path\"\n";
$message_part .= 'Content-ID: <'.$path['cid'].">\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= "--$boundary\n".$message_part."\n";
}
$multipart .= "--$boundary--\n";
return array('multipart' => $multipart, 'headers' => $headers);
}
What worked for me was to rename the project by removing the special characters.
Example: "project_marketplace" to "projectmarketplace"
In this case, I redid the project with react-native init and copied the src and package.json folder.
If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period
public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
AsyncTask<Params, Progress, Result> {
private static final int HTTP_REQUEST_TIMEOUT = 30000;
@Override
protected Result doInBackground(Params... params) {
createTimeoutListener();
return doInBackgroundImpl(params);
}
private void createTimeoutListener() {
Thread timeout = new Thread() {
public void run() {
Looper.prepare();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AsyncTaskWithTimer.this != null
&& AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
AsyncTaskWithTimer.this.cancel(true);
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, HTTP_REQUEST_TIMEOUT);
Looper.loop();
}
};
timeout.start();
}
abstract protected Result doInBackgroundImpl(Params... params);
}
A Sample for this
public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {
@Override
protected void onCancelled(Void void) {
Log.d(TAG, "Async Task onCancelled With Result");
super.onCancelled(result);
}
@Override
protected void onCancelled() {
Log.d(TAG, "Async Task onCancelled");
super.onCancelled();
}
@Override
protected Void doInBackgroundImpl(Void... params) {
// Do background work
return null;
};
}
This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;
ArrayList<String> recordings = new ArrayList<String>();
this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.
To show only running containers use the given command:
docker ps
To show all containers use the given command:
docker ps -a
To show the latest created container (includes all states) use the given command:
docker ps -l
To show n last created containers (includes all states) use the given command:
docker ps -n=-1
To display total file sizes use the given command:
docker ps -s
The content presented above is from docker.com.
In the new version of Docker, commands are updated, and some management commands are added:
docker container ls
It is used to list all the running containers.
docker container ls -a
And then, if you want to clean them all,
docker rm $(docker ps -aq)
It is used to list all the containers created irrespective of its state.
And to stop all the Docker containers (force)
docker rm -f $(docker ps -a -q)
Here the container is the management command.
If the path is correct and the name of the image is OK, but you are still getting the error
use:
from skimage import io
img = io.imread(file_path)
instead of:
cv2.imread(file_path)
The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
You can also use START WITH
to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,
SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
spring.jackson.serialization-inclusion=non_null
used to work for us
But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.
Now, another property spring.jackson.default-property-inclusion=non_null
is doing the magic.
in fact, serialization-inclusion
is deprecated. This is what my intellij throws at me.
Deprecated: ObjectMapper.setSerializationInclusion was deprecated in Jackson 2.7
So, start using spring.jackson.default-property-inclusion=non_null
instead
To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter
configured for the locale from which you're reading the string.
Different locales will format numbers differently. For example, in some parts of the world, COMMA
is used as a decimal separator while in others it is PERIOD
— and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.
It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter
for the way your input is formatted and use -[NSFormatter numberFromString:]
to get an NSNumber
from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:]
instead.
Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
It is recommended to use the spinal-case (which is highlighted by RFC3986), this case is used by Google, PayPal, and other big companies.
source:- https://blog.restcase.com/5-basic-rest-api-design-guidelines/
I know this is an old post, but check out the Extended WPF Toolkit. It has a RichTextBox that supports what you are tryign to do.
In Eclipse + PyDev, Python block commenting is similar to Eclipse Java block commenting; select the lines you want to comment and use Ctrl + / to comment. To uncomment a commented block, do the same thing.
If you use any() when mocking, you have to relpace @RunWith(MockitoJUnitRunner.class)
with
@RunWith(MockitoJUnitRunner.Silent.class)
.
If your mongoDB server(remote server)'s version is greater then 4.0.3, then you will face this issue. Hence you should replace your current mongo-client shell with below mongo :
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
Then you mongo client will be able to connect your remove mongodb
View Demo which is using angularjs
and see your's browser log
<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {
console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 5000;
// Start a timeout
var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
var bodyElement = angular.element($document);
/// Keyboard Events
bodyElement.bind('keydown', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('keyup', function (e) { TimeOut_Resetter(e) });
/// Mouse Events
bodyElement.bind('click', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousemove', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('DOMMouseScroll', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousewheel', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousedown', function (e) { TimeOut_Resetter(e) });
/// Touch Events
bodyElement.bind('touchstart', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('touchmove', function (e) { TimeOut_Resetter(e) });
/// Common Events
bodyElement.bind('scroll', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('focus', function (e) { TimeOut_Resetter(e) });
function LogoutByTimer()
{
console.log('Logout');
///////////////////////////////////////////////////
/// redirect to another page(eg. Login.html) here
///////////////////////////////////////////////////
}
function TimeOut_Resetter(e)
{
console.log('' + e);
/// Stop the pending timeout
$timeout.cancel(TimeOut_Thread);
/// Reset the timeout
TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
}
})
</script>
</html>
Below code is pure javascript version
<html>
<head>
<script type="text/javascript">
function logout(){
console.log('Logout');
}
function onInactive(millisecond, callback){
var wait = setTimeout(callback, millisecond);
document.onmousemove =
document.mousedown =
document.mouseup =
document.onkeydown =
document.onkeyup =
document.focus = function(){
clearTimeout(wait);
wait = setTimeout(callback, millisecond);
};
}
</script>
</head>
<body onload="onInactive(5000, logout);"></body>
</html>
I updated my solution as @Tom suggestion.
<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {
console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 5000;
// Start a timeout
var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
var bodyElement = angular.element($document);
angular.forEach(['keydown', 'keyup', 'click', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'scroll', 'focus'],
function(EventName) {
bodyElement.bind(EventName, function (e) { TimeOut_Resetter(e) });
});
function LogoutByTimer(){
console.log('Logout');
///////////////////////////////////////////////////
/// redirect to another page(eg. Login.html) here
///////////////////////////////////////////////////
}
function TimeOut_Resetter(e){
console.log(' ' + e);
/// Stop the pending timeout
$timeout.cancel(TimeOut_Thread);
/// Reset the timeout
TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
}
})
</script>
</html>
Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:
var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];
I know this is really old post but here is a simple solution to work with dynamic
type in c#
.
- can use simple reflection to enumerate direct properties
- or can use the
object
extention method- or use
GetAsOrDefault<int>
method to get a new strongly typed object with value if exists or default if not exists.
public static class DynamicHelper
{
private static void Test( )
{
dynamic myobj = new
{
myInt = 1,
myArray = new[ ]
{
1, 2.3
},
myDict = new
{
myInt = 1
}
};
var myIntOrZero = myobj.GetAsOrDefault< int >( ( Func< int > )( ( ) => myobj.noExist ) );
int? myNullableInt = GetAs< int >( myobj, ( Func< int > )( ( ) => myobj.myInt ) );
if( default( int ) != myIntOrZero )
Console.WriteLine( $"myInt: '{myIntOrZero}'" );
if( default( int? ) != myNullableInt )
Console.WriteLine( $"myInt: '{myNullableInt}'" );
if( DoesPropertyExist( myobj, "myInt" ) )
Console.WriteLine( $"myInt exists and it is: '{( int )myobj.myInt}'" );
}
public static bool DoesPropertyExist( dynamic dyn, string property )
{
var t = ( Type )dyn.GetType( );
var props = t.GetProperties( );
return props.Any( p => p.Name.Equals( property ) );
}
public static object GetAs< T >( dynamic obj, Func< T > lookup )
{
try
{
var val = lookup( );
return ( T )val;
}
catch( RuntimeBinderException ) { }
return null;
}
public static T GetAsOrDefault< T >( this object obj, Func< T > test )
{
try
{
var val = test( );
return ( T )val;
}
catch( RuntimeBinderException ) { }
return default( T );
}
}
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
Simply use:
int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
"Text",
JOptionPane.INFORMATION_MESSAGE,
null,
null,
"[sample text to help input]"));
You cannot cast a String
to an int
, but you can convert it using Integer.parseInt(string)
.
I saw a very good example today, from this blog post, as I summarize below.
Imagine you have a structure for nodes in a linked list, which probably is
typedef struct node
{
struct node * next;
....
} node;
Now you want to implement a remove_if
function, which accepts a removal criterion rm
as one of the arguments and traverses the linked list: if an entry satisfies the criterion (something like rm(entry)==true
), its node will be removed from the list. In the end, remove_if
returns the head (which may be different from the original head) of the linked list.
You may write
for (node * prev = NULL, * curr = head; curr != NULL; )
{
node * const next = curr->next;
if (rm(curr))
{
if (prev) // the node to be removed is not the head
prev->next = next;
else // remove the head
head = next;
free(curr);
}
else
prev = curr;
curr = next;
}
as your for
loop. The message is, without double pointers, you have to maintain a prev
variable to re-organize the pointers, and handle the two different cases.
But with double pointers, you can actually write
// now head is a double pointer
for (node** curr = head; *curr; )
{
node * entry = *curr;
if (rm(entry))
{
*curr = entry->next;
free(entry);
}
else
curr = &entry->next;
}
You don't need a prev
now because you can directly modify what prev->next
pointed to.
To make things clearer, let's follow the code a little bit. During the removal:
entry == *head
: it will be *head (==*curr) = *head->next
-- head
now points to the pointer of the new heading node. You do this by directly changing head
's content to a new pointer.entry != *head
: similarly, *curr
is what prev->next
pointed to, and now points to entry->next
.No matter in which case, you can re-organize the pointers in a unified way with double pointers.
I want to understand the lock each transaction isolation takes on the table
For example, you have 3 concurrent processes A, B and C. A starts a transaction, writes data and commit/rollback (depending on results). B just executes a SELECT
statement to read data. C reads and updates data. All these process work on the same table T.
WHERE aField > 10 AND aField < 20
, A inserts data where aField
value is between 10 and 20, then B reads the data again and get a different result.I want to understand where we define these isolation levels: only at JDBC/hibernate level or in DB also
Using JDBC, you define it using Connection#setTransactionIsolation
.
Using Hibernate:
<property name="hibernate.connection.isolation">2</property>
Where
Hibernate configuration is taken from here (sorry, it's in Spanish).
By the way, you can set the isolation level on RDBMS as well:
SET ISOLATION TO DIRTY READ
sentence.)and on and on...
Stream.of().mapToInt().toArray()
seems to be the best options.
int[] arr = Stream.of(new String[]{"1", "2", "3"})
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );
To change the indentation based on programming language:
Open the Command Palette (CtrlShiftP | macOS: ??P)
Preferences: Configure language specific settings... (command id: workbench.action.configureLanguageBasedSettings
)
Select programming language (for example TypeScript)
Add this code:
"[typescript]": {
"editor.tabSize": 2
}
If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?
If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.
>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'
test.py:
def run():
return "Hello world!"
If you're using Python 3.1 or later, you should also take a look at importlib.
Define the class before you use it:
class Something:
def out(self):
print("it works")
s = Something()
s.out()
You need to pass self
as the first argument to all instance methods.
For me perfectly fork this code.
$('#dom_object_id').on('change paste keyup', function(){
console.log($("#dom_object_id").val().length)
});
Key event for .on() function is "paste" to get changes dynamically
PHP version of the Gumbo algorithm: http://sandbox.onlinephpfunctions.com/code/51e1b05dac2e648fd13e0b60f44a2abe1e4a8689
$numbers = [10, 9, 2, 3, 4, 5, 6, 7];
$largest = $numbers[0];
$secondLargest = null;
for ($i=1; $i < count($numbers); $i++) {
$number = $numbers[$i];
if ($number > $largest) {
$secondLargest = $largest;
$largest = $number;
} else if ($number > $secondLargest) {
$secondLargest = $number;
}
}
echo "largest=$largest, secondLargest=$secondLargest";
I think it should be the case. To erase the character, you should use replace(".", "")
instead.
If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.
SHOW CREATE TABLE alarm;
Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`)
line.ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
ALTER TABLE `alarm` DROP `server_id`
This will delete the foreign key server from the Alarms table.
Simply you can use padding-top
and padding-bottom
on a td
element.
Unit can anything from this list:
td_x000D_
{_x000D_
padding-top: 10px;_x000D_
padding-bottom: 10px;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<th>Firstname</th>_x000D_
<th>Lastname</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Peter</td>_x000D_
<td>Griffin</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Lois</td>_x000D_
<td>Griffin</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Use
sudo pip install virtualenv
Apparently you will have powers of administrator when adding "sudo" before the line... just don't forget your password.
We had a similar issue. Uploaded builds were queueing up and it simply said "Processing" with the popup help, “After builds are uploaded they will go through a processing state before they can be used.” Days passed.
Selecting "Internal Testers," making a change, and saving seemed to immediately clear the queue: The latest build was now active and available for testing. I've done this twice with two different apps now.
Update: At this point, all bets are off. It seems "processing" happens when Apple quietly upgrades iTunes Connect and there's nothing you can do about it.
On September 23, 2015 iTunes Connect didn't accept any uploads for nearly 24 hours. The "Internal Testers" trick didn't work. Eventually bumping the version number (to avoid "duplicate binary" error) and re-submitting worked.
The next day, Surprise! iTunes Connect was completely changed. I guess we were all looking at a dead site while they brought up the new version in the background :(
In our case we can still see dozens of "failed" uploads still sitting in the "processing" state. Oh well.
Some people report using Application Loader works better than Xcode for submitting builds to iTunes Connect. You can find it inside Xcode now, under the Xcode menu "Open Developer Tool" item.
Sometimes this works. Sometimes it doesn't. Your milage may vary ¯\_(?)_/¯
Check what git remote -v
returns: the account used to push to an http url is usually embedded into the remote url itself.
https://[email protected]/...
If that is the case, put an url which will force Git to ask for the account to use when pushing:
git remote set-url origin https://github.com/<user>/<repo>
Or one to use the Fre1234 account:
git remote set-url origin https://[email protected]/<user>/<repo>
Also check if you installed your Git For Windows with or without a credential helper as in this question.
The OP Fre1234 adds in the comments:
I finally found the solution.
Go to:Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials
Under
Generic Credentials
there are some credentials related to Github,
Click on them and click "Remove
".
That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper
output (it should be manager
)
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the evente
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
Check if its not already defined, otherwise defines it on the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
A standard prolog predicate will do this.
isfive(5).
will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use \=
isNotEqual(A,B):- A\=B.
Technically it is does not unify, but it is similar to not equal.
Learn Prolog Now is a good website for learning prolog.
Edit: To add another example.
isEqual(A,A).
I go with
HttpContext.Current.Request.ServerVariables["HTTP_HOST"]
You should use Asset Catalog:
I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.
Note: No need to make any entry in info.plist file :) And no any other configuration.
In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.
Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon.
If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution.
After uploading all required dimensions, you shouldn't get any warning.
Note that if typing if ( exists $hash{ key } )
isn’t too much work for you (which I prefer to use since the matter of interest is really the presence of a key rather than the truthiness of its value), then you can use the short and sweet
@hash{@key} = ();
There are limitations in PUT over PATCH while making updates. Using PUT requires us to specify all attributes even if we want to change only one attribute. But if we use the PATCH method we can update only the fields we need and there is no need to mention all the fields. PATCH does not allow us to modify a value in an array, or remove an attribute or array entry.
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
Using the java.time
framework built into Java 8 and later.
import java.time.Instant;
Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900
This works in UTC because Instant.now()
is really call to Clock.systemUTC().instant()
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
Another option, in the host you run rsync from, set the port in the ssh config file, ie:
cat ~/.ssh/config
Host host
Port 2222
Then rsync over ssh will talk to port 2222:
rsync -rvz --progress --remove-sent-files ./dir user@host:/path
The problem is that you don't have a route for /
. Change your definition to this:
ShopMyShopBundle_homepage:
pattern: /
defaults: { _controller: ShopMyShopBundle:Main:index }
requirements:
_method: GET
This function will return array with Header values as array keys.
function csv_to_array($file_name) {
$data = $header = array();
$i = 0;
$file = fopen($file_name, 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if( $i==0 ) {
$header = $line;
} else {
$data[] = $line;
}
$i++;
}
fclose($file);
foreach ($data as $key => $_value) {
$new_item = array();
foreach ($_value as $key => $value) {
$new_item[ $header[$key] ] =$value;
}
$_data[] = $new_item;
}
return $_data;
}
A Simple Solution: It work's for me
<div class="form-group">
<label for="mcategory">Select Category</label>
<select class="form-control" id="mcategory" name="mcategory" required>
<option value="">Please select category</option>
<?php foreach ($result_cat as $result): ?>
<option value="<?php echo $result['name'];?>"<?php
if($result['name']==$mcategory){
echo 'selected';
} ?>><?php echo $result['name']; ?></option>
}
<?php endforeach; ?>
</select>
</div>
... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...
It ought to work.
For Android SDK, setEndpoint solves the problem, although it's been deprecated.
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
context, "identityPoolId", Regions.US_EAST_1);
AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
s3.setEndpoint("s3.us-east-2.amazonaws.com");
I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc
Option 1
Create Procedure [Test] AS
DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10)
Set @StartDate = '201620' --Define start YearWeek
Set @EndDate = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Option 2
Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Then run exec test '2016-01-01','2016-01-25'
Or you can try:
find . -name '*.pdf' -exec rm -f {} \;
Simply...
$('#myForm').submit(function() {
return confirm("Click OK to continue?");
});
or
$('#myForm').submit(function() {
var status = confirm("Click OK to continue?");
if(status == false){
return false;
}
else{
return true;
}
});
You can try this quick code
public static void cancelNotification(Context ctx, int notifyId) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
nMgr.cancel(notifyId);
}
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
}
you set AllowRating property to true from your controller or model
@Html.CheckBoxFor(m => m.AllowRating, new { @checked =Model.AllowRating })
Here is what worked for me.
I Have used rename command so that if any file contains spaces in name of it then , mv command dont get confused between spaces and actual file.
Here i replaced spaces , ' ' in a file name with '_' for all jpg files
#! /bin/bash rename 'y/ /_/' *jpg #replacing spaces with _ let x=0; for i in *.jpg;do let x=(x+1) mv $i $x.jpg done
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html
w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).
for widget in frame.winfo_children():
widget.destroy()
Will destroy all the widget in your frame. No need for a second frame.