_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 21
37k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d1007
|
train
|
the logic of your formula may be correct, but more factors must be considered when playing with the calendar as humanity likes to adjust even the rules of adjustment. here are a few examples:
*
*the longest year in history: 46 BCE (708 AUC) lasting 445 days known as "the last year of confusion" as Ceasar added 3 more months (90 days) so that the next year (45 BCE) would start right after the winter solstice.
*the shortest year in history: 1582 CE lasting 355 days where October had only 21 days (4th Oct. was followed by 15th Oct.) but also it depends where you are
because British Empire decided to reinvent the wheel by accepting the "1582-wheel" in the year 1752 CE where September had only 19 days (2nd Sep. was followed by 14th Sep.) resulting the year to have 355 days as well. however, if we are technical, the British Empire also had a year that lasted only 282 days because their "old" new year started on 25 March and not 1 January therefore the year 1751 CE started on 25th Mar and ended on 31st Dec. Turkey, for example, joined the "gregorian train" in 1st Jan 1927 CE after their December of 1926 CE had only 18 days so that year was long only 352 days. the latest country to adopt the gregorian calendar was Saudi Arabia in 2016 CE when they jumped from 1437 AH
*the year zero: does not exist. 31st Dec. 1 BCE was followed by 1st Jan. 1 CE
753 AUC = 1 BCE
754 AUC = 1 CE
also, dude who invented this nonsense was born around 1223 AUC (470 CE) so that speaks for itself. this is important because offsetting DATEVALUE needs to be done in such a way that the calculation will not cross 0 eg. not drop bellow -693593:
=TO_DATE(-694324) - incorrect datevalue - 01/01/00-1
=TO_DATE(-693678) - incorrect datevalue - 08/10/0000
=TO_DATE(-693593) - 1st valid datevalue - 01/01/0001
=TO_DATE(35830290) - last valid datevalue - 31/12/99999
*it's also worth mentioning that 25th Dec. 200 CE was not Friday on the Roman peninsula because people in that era used 8-day system
*there are many calendar systems each with its own set of rules and up to this date there are still countries that do not recognize the gregorian calendar as a standard so if you want to re-live the year 2021 go to Ethiopia where today's 9 Oct. 2022 CE = 29 Mes. 2015 EC on the other hand if you prefer to live in the future try Nepal where today's 9 Oct. 2022 = 23 Ash. 2079 BS
|
unknown
| |
d1009
|
train
|
You could look at the table.assign(<new column> = <formula>) function to build out your dataframe.
|
unknown
| |
d1013
|
train
|
Timsort is stable, which means that you can get what you want with something like
>>> assert not message.islower()
>>> ''.join(sorted(message, key=lambda c: not c.isupper())).upper()
'HAPPY NEW MONTH'
The trick is that booleans are a subclass of integers in python. The key returns False == 0 for elements you want to move to the beginning, and True == 1 for elements that stay. You need to use lambda c: not c.isupper() because spaces and other characters will move back if you use str.islower as the key.
If you want the assertion to be more detailed, like checking if all the letter characters are lowercase, you can do it with something like
>>> assert any(c != c.lower() for c in message)
For more complex unicode code points, use c.casefold() instead of c.lower().
A: Here is a solution that uses a single list comprehension without imports. It is also linear in time with the length of the string unlike sorting solutions with have higher time complexity of O(n log n). It also has an assertion statement flagging strings with no uppercase letters (i.e., all alpha characters are lowercase).
def unravel_message(s):
assert any('A' <= c <= 'Z' for c in s)
return (duo := list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s]))))[0] + duo[1]
x = unravel_message(' neHAw moPPnthY')
print(x)
x = unravel_message(' no uppercase letters')
Output:
HAPPY NEW MONTH
Traceback (most recent call last):
File "C:\python\test.py", line 7, in <module>
x = unravel_message(' no uppercase letters')
File "C:\python\test.py", line 2, in unravel_message
assert any('A' <= c <= 'Z' for c in s)
AssertionError
Note that the solution uses the walrus operator := to make it a one-liner. If you are using Python earlier than version 3.8, you can do this instead:
def unravel_message(s):
assert any('A' <= c <= 'Z' for c in s)
duo = list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s])))
return duo[0] + duo[1]
|
unknown
| |
d1015
|
train
|
It is possible, but you'll need to do some work to get them calling properly. I've never done it myself, but until someone better equipped to answer the question comes along here's a few places to start.
Take a look at the JNI (Java Native Interface, google or wikipedia can tell you more), which lets you call out from Java to other languages. There seems to be a project called jni4net ( http://jni4net.sourceforge.net ) which is intended to do exactly what you want, but it's in alpha at the moment and might not be stable enough. Still it could be worth having a look.
You can also do it yourself, calling through the JNI as a C call which will then get through to the CLR eventually, but it looks like a lot of effort. I know this isn't a quick and easy solution, but it might give you a couple of places to get started. also http://www.codeproject.com/KB/cross-platform/javacsharp.aspx seemed to be a fairly good look at how to go about it.
As all of the other answers so far have said though, it's fiddly and a pain. If you can do something else instead, it will probably be worth it.
A: Have a look at Jni4Net and this stack overflow question: is there an effective tool to convert c# to java?
A: You would have to use native calls which would a) be really irritating to keep up to date and B) defeat the huge advantage of java being cross-platform.
Your best bet might be to try to find something that can convert C# to java--or better yet recode your C# code into java.
In the long run it will save you a lot of stress.
A: No sure about this possibility but your idea is not so good.
You still can use COM or hook or try ngen but this ways all are weird.
Java is very similar C# . Try to code in Java or something like stab , I think that is much easer to code in some JVM-based langue for jvm.
A: Diferent compilers dud, it's not possible. Unless You use java sharp language in visual studio, then the compilers mach.
|
unknown
| |
d1017
|
train
|
Please look up https://gojs.net/latest/samples/index.html
- these are javascript based
- Individual classes are also available (which you can customize for a new visualization)
- It can be installed via npm, and, if you don't like it, can be easily removed from the system.
I hope this helps.
regards
SS
|
unknown
| |
d1023
|
train
|
You must run this program as administrator in order for it to work correctly. I just tested it working and GetLastError() = 0 after each line, which means there were no problems.
|
unknown
| |
d1027
|
train
|
Something like this ought to work
import tensorflow as tf
import numpy as np
def y_pred(x, w):
return [x[0]*w[0]+x[1]*w[0], x[2]*w[1]+x[3]*w[1]]
def loss_fun(y_true, y_pred):
return tf.reduce_sum(tf.pow(y_pred - y_true, 2))
x = np.array([1, 2, 3, 4], dtype="float32")
y_true = np.array([10, 11], dtype="float32")
w = tf.Variable(initial_value=np.random.normal(size=(2)), name='weights', dtype=tf.float32)
xt = tf.convert_to_tensor(x)
yt = tf.convert_to_tensor(y_true)
sgd_opt = tf.optimizers.SGD()
training_steps = 100
display_steps = 10
for step in range(training_steps):
with tf.GradientTape() as tape:
tape.watch(w)
yp = y_pred(xt, w)
loss = loss_fun(yt, yp)
dl_dw = tape.gradient(loss, w)
sgd_opt.apply_gradients(zip([dl_dw], [w]))
if step % display_steps == 0:
print(loss, w)
|
unknown
| |
d1029
|
train
|
In general, this used to be not allowed by design. It's a violation of the sandbox.
From Wikipedia -> Javascript -> Security:
JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-relatedactions, not general-purpose programming tasks like creating files.
However, it's now possible in current browsers using the FILE API specification.
This should in theory allow you to read it using the FileReader interface, although you might need to use something like JSON.parse() (or $.parseJSON if you're using JQuery) to then interpret it in the way you need. Lots more detail and examples of how to do this are here:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
|
unknown
| |
d1037
|
train
|
To validate html forms , the simplest way is to combine two open source powerful frameworks twitter bootstrap ( to get nice form ) and jquery.validate.js plugin ( for validation ).
Bootstrap framework : http://getbootstrap.com/getting-started/ .
Jquery validation plugin : http://jqueryvalidation.org/
So your html code and your script may appear like this
Html code :
First add this link
<link href="bootstrap/bootstrap.min.css" rel="stylesheet" media="screen">
Then
<form method="post" action="/User/AddExperience" id="add-experience-form" class="form-horizontal">
<fieldset>
<h4 class="text-primary">fields required * </h4>
<div class="form-group">
<div class="control-group">
<label class="control-label col-xs-3" for="experienceTitle">Experience Title<span class="req">*</span></label>
<div class="col-xs-9">
<input type="text" class="form-control" id="eventTitle" name="eventTitle">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-9">
<div class="form-actions">
<input type="submit" class="btn btn-primary" name="newsubmit" id="newsubmit" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</div>
</div>
</fieldset>
</form>
Jquery script : put it in a js file called validate.js
$(document).ready(function(){
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
});
$('#add-experience-form').validate({
rules: {
eventTitle: {
minlength: 2,
lettersonly:true,
required: true
}
},
messages: {
eventTitle: {
required:"blablabla",
minlenght:"blablabla",
maxlenght:"50 character maximum",
lettersonly: "Letters only please"
}
},
highlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('error').addClass('success');
},
success: function (label) {
$(label).closest('form').find('.valid').removeClass("invalid");
},
errorPlacement: function (error, element) {
element.closest('.control-group').find('.help-block').html(error.text());
}
}).cancelSubmit=true; // to block the submit of this plugin and call submit to php file
});
You can put all these scripts in one folder called js then add them in your code
<script src="//code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/docs.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/validate.js"></script>
For more details you can refer to the documentation http://jqueryvalidation.org/documentation/
|
unknown
| |
d1039
|
train
|
Use the jQuery outerWidth function to retrieve the width inclusive of padding, borders and optionally margin as well (if you send true as the only argument to the outerWidth method).
A: Tested Solution: Find height of a div and use it as margin top of another div.
$('.topmargindiv').css('margin-top', function() {
return $('.divheight').height();
});
|
unknown
| |
d1043
|
train
|
Classic confusion caused by extending JPanel and using another JPanel. Replace frame.getContentPane().add(secPanel) with frame.add(this , BORDERLAYOUT.CENTER) and everything should work fine.
A: You are calling super.paintComponents(g); in paintComponent, not the s at the end, this is going to cause a StackOverflowException eventually, but don't actually ever add the ReadingImage JPanel to anything, so it's never actually painted
This means that there doesn't seem to be any point any point to the secPane
You should also avoid creating frames from within other components, especially from within the constructor, it provides a very limit use case for the component
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ReadingImage extends JPanel {
private BufferedImage img;
public ReadingImage(String path) {
try {
FileImageInputStream fi = new FileImageInputStream(new File(path));
img = ImageIO.read(fi);
this.repaint();
} catch (IOException io) {
io.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
repaint();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame();
frame.add(new ReadingImage("Your image"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300, 300);
frame.setSize(300, 500);
frame.setVisible(true);
}
});
}
}
I'm not sure exactly what you are trying to achieve, but I would also encourage you to override the ReadingImage's getPreferredSize method and return the size of the image, this makes it easier to layout
A: first load the image in Image Icon, lets say the object as 'pic'.
panel1.add(new JLabel(pic));
add and set panel1 to visible.
|
unknown
| |
d1045
|
train
|
One approach is to collect the "failed" paths for each sender, and return the path collections that have more than 10 items:
MATCH path = (a:Sender)-[:FAILED_TO]->(r:Recipient)
WITH a, COLLECT(path) AS paths
WHERE SIZE(paths) > 10
RETURN paths
|
unknown
| |
d1047
|
train
|
Since it's a table, I'd suggest structured references like:
=COUNTIF(Table1[[#Headers],[Product]]:[@Product],[@Product])
A: I don't get the same results as you do -- when I insert a row, the criteria cell changes.
In any event, since this is a Table, you can use structured references:
B2: =COUNTIF(INDEX([Product],1):@[Product],@[Product])
A: David, if your cells are not formatted as an Excel Table, this formula can do the job:
=COUNTIF(INDIRECT("A1:A" & COUNTA(A:A)),A1)-COUNTIF(INDIRECT("A"&ROW() & ":A" & COUNTA(A:A)),A1)+1
|
unknown
| |
d1049
|
train
|
The second image are default references. If you set them they are automatically applied after adding this script to an object.
They are not required. And only apply to a script added via the Editor (not by script!). What matters later on runtime are only the values on the GameObject.
Further you can only reference assets from the Assets folder here. They make sense e.g. if you have a button script that uses a certain Click sound, a texture and e.g. a prefab. For these three you now could already define default values so someone using your component doesn't have to assign everything everytime but already has the default references as a kind of fallback.
So in your case it would only make sense, if the borders are prefabs from the Assets that are spawned by this script. The FoodPrefab is even called like this and makes sense to have as a default reference so you don't have to drag it into each and every instance of SpawnFood you create.
And btw just by looking at your settings you should probably directly make your fields of type RectTransform so you can't accidentally reference another object there.
|
unknown
| |
d1051
|
train
|
This is a sandbox problem. The browser does not allow loading local resources for security reasons. If you need it still, use a local webserver on your machine.
A: Most major browsers don't allow you to load in local files, since that poses a security error, e.g. people stealing secure files.
You need to test this on localhost, or setup some other server to test it.
Or, if you're using Chrome, you can turn on the flag that'll allow you to load in local files.
chrome --allow-file-access-from-files
run this from command line
|
unknown
| |
d1053
|
train
|
$('article *',document.body).click(
function(e){
e.stopPropagation();
var selectedElement = this.tagName;
$(selectedElement).css('border','1px dotted #333');
}
);
Demo at JS Bin, albeit I've used the universal selector (since I only posted a couple of lists (one an ol the other a ul).
Above code edited in response to comments from @Peter Ajtai, and linked JS Bin demo up-dated to reflect the change:
Why run around the block once before you look at the tagName? How about var selectedElement = this.tagName;. Also it's e.stopPropagation(), since you're calling a method.
A: I don't know how many elements are nested under your article elements, but it would seem wasteful to add click event handlers to all of them using *.
Instead, just add the handler to article, and get the tagName of the e.target that was clicked.
$("article", document.body).click(function ( e ) {
e.stopPropagation();
$( e.target.tagName ).css("border", "1px dotted #333")
});
This will be much more efficient.
|
unknown
| |
d1059
|
train
|
The following snippet hides the navigation bar and status bar:
window.decorView.apply {
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
}
From https://developer.android.com/training/system-ui/navigation
Nonetheless for your case you need two things to happen.
*
*First, set windowFullScreen to true to allow the dialog to paint every pixel in the screen. (i.e. Use any FullScreen theme).
*Then, on you dialog, set the systemUiVisibility to View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION.
This will stop the navigationBar from ever showing until you reset the flags or dismiss the dialog.
The complete snippet:
class SomeActivity {
fun showDialog() {
FullScrenDialog()
.apply {
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_NoTitleBar_Fullscreen)
}
.show(supportFragmentManager, "TAG")
}
}
class FullScrenDialog : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
dialog.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
return inflater.inflate(R.layout.dialog, container)
}
}
A: Please try below code for dialog:
final Dialog dialog = new Dialog(this);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setGravity(Gravity.CENTER);
dialog.setContentView(R.layout.dialog_logout);
Window window = dialog.getWindow();
window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
window.getDecorView().setSystemUiVisibility(uiOptions);
dialog.show();
Output is:
I hope it works for you.
|
unknown
| |
d1065
|
train
|
ROWID is a unique identifier of each row in the database.
ROWNUM is a unique identifier for each row in a result set.
You should be using the ROWNUM version, but you will need an ORDER BY to enforce a sorting order, otherwise you won't have any guarantees what is the "first" row returned by your query and you might be updating another row.
update addrView
set home='current'
where (tl, tr) = (
select tl, tr
from (select tl, tr
from addrView
where (tl = '7' and tr = '2')
order by col_1
, col_2
, col_3 etc.
) result_set
where rownum = 1);
But, if you don't care about what data is in the first row returned by your query, then you can use only rownum = 1.
update addrView
set home = 'current'
where (tl = '7' and tr = '2')
and rownum = 1;
|
unknown
| |
d1067
|
train
|
You missed each:
And match each response.errors[*].reason contains "this is reason"
Refer: https://github.com/karatelabs/karate#match-each
|
unknown
| |
d1069
|
train
|
What you're describing is a state machine.
Older SO question discussing the various gems and plugins of the time, plus some basics.
Newer blog post discussing the hows and whys.
|
unknown
| |
d1073
|
train
|
*
*Every endorsing peer is also a committing peer.
*An orderer and a peer are totally different binaries, and have completely different APIs, so - you can't have one fill the role of the other.
|
unknown
| |
d1075
|
train
|
If you are asking how could I render navbar and sidebar to all components except login, then you can check the browser url.
There are many ways of doing this, but one of which is like following:
<Route path="*" render={props => <Layout {...props} />} />
This will appear for all your routes now. Then inside Layout, you can check the route, and only render something if the route does not equal to login.
render(){
if(this.props.location === "login"){return null}
...
}
While typing this, you can do it directly in React Router, maybe excluding certain route.
|
unknown
| |
d1077
|
train
|
I don't know how your tasks are coded, but it seems that they could be encapsulated in commands, which would then be put in a queue, or some other data structure. Once they are dequeued, their logic is checked. If they need to run, they are executed, and they're not put back in the queue. If their logic says that they shouldn't run, they're just put back in the queue to be able to run later.
Your interface would be something like:
public interface ITaskSink {
void AddTask(ICommandTask task);
}
public interface ICommandTask {
bool ShouldRun();
void Run(ITaskSink sink);
}
Tasks could also be able to add other tasks to the data structure (so Run takes an ITaskSink as a parameter), covering your subtask creation requirement. A task could even add itself back to the sink, obviating the need for the ShouldRun method and simplifying your task processor class.
A: If you're using .NET 4.0, the Lazy<T> generic might be the solution to what you're describing, because it evaluates its value at most once.
I'm not sure I exactly understand your use case, but there's no reason you couldn't nest Lazys together to accomplish the nested children issue.
A: I'm not exactly sure what you're talking about, but a helpful pattern for complex chained logic is the rules engine. They're really simple to code, and can be driven by simple truth tables, which are either compiled into your code or stored as data.
A: Create a private static variable, create a read only property to check for null on the private variable, if the variable is null instantiate/initialize and just return the private variable value. In your implementation code reference the property, never the private variable.
|
unknown
| |
d1087
|
train
|
Try looping through all ChartObjects in your worksheet, and delete each one of them (if exists).
Code:
Option Explicit
Sub CheckCharts()
Dim ChtObj As ChartObject
For Each ChtObj In Worksheets("Sheet1").ChartObjects '<-- modify "Sheet1" with your sheet's name
ChtObj.Delete
Next ChtObj
End Sub
|
unknown
| |
d1089
|
train
|
Make sure you include jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
IMPORTANT: Also put your code inside a document-ready function and I would suggest you to use jQuery click() function instead of the way you have done, but that's okay:
$(document).ready(function () {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function(){
if ($(this).children('a').hasClass('holder_notify_drop_link')){
$(this).on('click',function(e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick',"openFrame('"+url+"','yes')");
e.preventDefault();
});
};
)};
});
A: Here's a working example http://jsfiddle.net/g248G/.
HTML:
<div class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://stackoverflow.com">Stackoverflow.com</a>
</div>
<ul>
<li class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://google.com">Google.com</a>
</li>
</ul>
Javascript:
function openFrame(URL, option) {
window.open(URL);
}
$(document).ready(function() {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function() {
$(this).children('a').each(function() {
var $link = $(this);
if ($link.hasClass('holder_notify_drop_link')) {
var URL = $link.attr('href');
$link.on('click', function(event) {
event.preventDefault();
openFrame(URL, 'yes');
});
}
});
});
});
A: Why not use jQuery.on() for that?
This will bind click function to all current and future elements of a in holder_notify_drop_data container.
$('.holder_notify_drop_data').on('click', 'a', function (ev) {
ev.preventDefault();
openFrame($(this).prop('href'), 'yes');
});
|
unknown
| |
d1091
|
train
|
Yes you need to add an .CreateAleas
.CreateAlias("Product", "product", JoinType.InnerJoin)
please change JoinType to your need, and use "product" alias instead of property name "Product"
so final should be something like:
.CreateCriteria(typeof(ProductCategory))
.CreateAlias("Product", "product", JoinType.InnerJoin)
.Add(Restrictions.Eq("CompanyId", companyId))
.Add(Restrictions.Eq("CategoryId", id))
.Add(Restrictions.Eq("product.IsPopItem", true))
.List<ProductCategory>());
return products;
|
unknown
| |
d1093
|
train
|
To start, you might want to know this:
the first code you get to run after the application has finished launching, is the one you put in the Application Delegate in the method application:didFinishLaunchingWithOptions. The app delegate is the class that is set to receive general notifications about what's going on with the app, like it finished launching :)
The other kind of 'notifications' of changes in the state of the app, or the life cycle of views are:
-viewDidLoad
-viewWillAppear:animated:
-viewDidAppear:animated:
-viewWillDisappear:animated:
-viewDidDisappear:animated:
-viewDidUnload
Those methods are declared in UIViewController, and you can implement them in your UIViewController subclasses to customize the behaviour of a view in those situations (each method name is self explanatory)
The life cycle of an app is pretty well covered here: http://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf page 27
About showing a logo when the app launches, apps achieve that setting a "splash" image by putting its name in the info.plist property-list file, in the UILaunchImageFile key.
A: I think the official developer guide delivered by apple will help you. This is the link:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html
|
unknown
| |
d1097
|
train
|
Although it seems not to be mentioned in the documentation, I also experienced that classes annotated with @Test must have a void return type. If you need data provided by some other method, you could try the Data Provider mechanism of TestNG.
|
unknown
| |
d1099
|
train
|
It appears you are looking in the wrong place for the resource. You are looking in the XAML of the metro window however you should be looking in the main window XAML specify to the program where to look using something like this: (I am not currently on visual studio)
private void MetroWindow_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
tb = (TaskbarIcon)this.FindResource("TestNotifyIcon");
}
}
or
private void MetroWindow_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
tb = (TaskbarIcon)MainWindow.FindResource("TestNotifyIcon");
}
}
|
unknown
| |
d1105
|
train
|
I'm not sure that got the point, but try.
Public Sub CheckPrKey()
lastRow = Worksheets("ETM_ACS2").Range("A" & Rows.Count).End(xlUp).Row
lastRowdashboard = Worksheets("dashboard").Range("B" & Rows.Count).End(xlUp).Row
With Worksheets("ETM_ACS2")
For r = 2 To lastRow
If .Range("I" & r).Value = "Y"
If .Range("N" & r).Value < "100" Then
Worksheets("dashboard").Range("A" & lastRowdashboard + 1)=.Range("D" & r)
Worksheets("dashboard").Range("B" & lastRowdashboard + 1)=.Range("N" & r)
lastRowdashboard = lastRowdashboard +1
End if
End If
Next r
End With
End Sub
|
unknown
| |
d1107
|
train
|
You don't need to put your <link rel="stylesheet" href="blah-blah.css"> tag into head to make it work, but it's a bad practice, because it works slower and looks a bit bad, but I understand your situation :) Just put <link> at the end of the <body> and it'll work fine! For example:
File styles.css
p {
color: blue;
}
File index.html
<!DOCTYPE html>
<html>
<head>
<!-- Evil host holders didn't allow access this tag. Well, okay :D -->
</head>
<body>
<p>I am blue, da ba dee da ba dai!</p>
<link rel="stylesheet" href="styles.css"/>
</body>
</html>
|
unknown
| |
d1109
|
train
|
It's a bit unclear from your question. But I think you're trying to break from your while loop on finding the product entered. I changed the redundant for loop to an if statement, so that you can break from the while loop. Your break is just breaking from the for loop, not the while loop.
static ArrayList<Product> printOneLine() {
ArrayList<Product> oneLineList = new ArrayList<Product>();
Scanner oneLine = readDetails("Products-JavaBikes.txt");
while (oneLine.hasNextLine()) {
oneLineList.add(getProduct(oneLine.nextLine()));
System.out.print("Please enter a number:");
Scanner input = new Scanner (System.in);
if(input.nextInt() < oneLineList.size()) {
System.out.println(oneLineList.get(i));
break;
}
}
return oneLineList;
}
|
unknown
| |
d1115
|
train
|
A simple CSS only approach could be to float your list elements left and give them a width of 25% total. Maybe add some padding so they aren't touching. So a width of 23% and left and right padding of 1% for a total of 25%.
ul{list-style-type: none;}
li{float: left; width: 23%; padding: 0 1%;}
Demo
|
unknown
| |
d1117
|
train
|
master_list = []
for event in soup.find('dual').find_all('event'):
master_list.append(event)
for event in soup.find('int').find_all('event'):
master_list.append(event)
for event in soup.find('whatever').find_all('event'):
master_list.append(event)
print sorted(event)
You may have to write your own comparison function so that sorted knows how to sort the list.
|
unknown
| |
d1119
|
train
|
KReporter certainly the best Reporting tool in the Marketing for SugarCRM, regardless of edition - be it PRO, ENT, CORP or CE.
The new free Google Charts are really cool
A: I suggest KINAMU Reporter, http://www.sugarforge.org/projects/kinamureporter
|
unknown
| |
d1121
|
train
|
!imporant for apply css forcefully and effects same as bootstrap.
.form-control:focus{
box-shadow: 0 0 5px rgba(81, 203, 238, 1) !important;
border: 1px solid rgba(81, 203, 238, 1) !important;
}
Working Fiddle
A: If you want an input to have a different/special appearance once selected, use the :focus CSS pseudo-class.
A simple example:
#myInput:focus {
border: 1px solid red;
}
PS. I assume you mean "glow", not "grow", and certainly not "blow" :-)
|
unknown
| |
d1125
|
train
|
There is a compilation error in your project
You must add derbynet.jar dependency in your classpath in order to embed the server.
http://db.apache.org/derby/papers/DerbyTut/ns_intro.html#ns_config_env
Client and server dependencies are two different jar.
|
unknown
| |
d1131
|
train
|
An ALB listener can only listen on a single port. You must define a listener for each port you want the load balancer to listen on. This isn't a limitation of Terraform, it's the way AWS load balancers are designed.
Additionally, since an ALB can only handle HTTP and HTTPS requests you usually don't setup more than two listeners on an ALB (ports 80 and 443), and the listener configuration would of necessity be different since one would have an SSL certificate configuration and one would not.
|
unknown
| |
d1133
|
train
|
I seen content overlapping when closing sidebars. May be you want to stop overlapping during open and close sidebar. It can be fixed by css. You can use transition in .wrapper class. see bellow code:
.wrapper{
height: 100%;
transition:all .25s;
}
A: You can achieve this with pure CSS.
You haven't specified what the requirements are, but you can use flexbox like the below example to achieve a max-width main container flanked by 2 compressing sidebars.
body {
margin: 0;
}
.wrapper{
display: flex;
}
main {
width: 1200px;
padding: 20px;
background-color: #f1f1f1;
}
.sidebar {
flex-grow: 1;
height: 100vh;
padding: 0 15px;
}
.sidebar-left {
border-right: 1px solid #06A52B;
}
.sidebar-right {
border-left: 1px solid #06A52B;
}
<div class="wrapper">
<aside class="sidebar sidebar-left">
<h2>Left sidebar</h2>
<p>Add content here</p>
</aside>
<main>
<h1>Max width of this block is 1200px</h1>
</main>
<aside class="sidebar sidebar-right">
<h2>Right sidebar</h2>
<p>Add content here</p>
</aside>
</div>
A: You Can Dynamic every css class Using [ngClass] Depending on your logic ..it will render when the value will change..
|
unknown
| |
d1135
|
train
|
I recently had this issue with my app.
I was getting the 'Error: secret option required for sessions' ONLY when deployed to Heroku.
Here is what my code looked like originally:
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}))
When I deployed to Heroku it kept giving me an "Internal server error". Once checking the logs, it showed me 'Error: secret option required for sessions'.
Here is how I fixed it:
app.use(session({
secret: 'secretidhere',
resave: false,
saveUninitialized: false
}))
Since my .env file wasn't viewable and that's where I had my secret code, it was giving me that error. Now, just by putting an arbitrary string 'secretidhere', I deployed to heroku again and it worked!
** However, please note that this should not be a permanent solution. As the poster above states, you should have a config file in your root directory, or another method so this session stays secret.
Hope this helps!
A: I was facing the same issue while I was deploying my code into AWS Elastic BeanStalk.
In .env we could have -
secret='my_secret'
While in server.js:
app.use(cookieParser())
app.use(session({
resave:true,
saveUninitialized:true,
secret:process.env.secret,
cookie:{maxAge:3600000*24}
}))
The solution turned out to be adding secret to the environments in there. Just add it to your enviroments for production, be it heroku or AWS.
A: Have you added your secret session from your .env file to heroku config? Since your .env is in your .gitignore it will not be pushed up to heroku. Your code is looking for a string from your process.env but the heroku environment does not have it yet.
You have two solutions
*
*Go to your app console and click on settings. Once you are there, click on the box that says reveal config vars and add your secret there.
or
*In the root directory of your project you can set your config vars there using the command
heroku config:set SECRET_SESSION="secretName"
|
unknown
| |
d1141
|
train
|
You don't need to cast it to NSString to use stringByReplacingCharactersInRange you just need to change the way you create your string range as follow:
update: Xcode 7.2 • Swift 2.1.1
let binaryColor = "000"
let resultString = binaryColor.stringByReplacingCharactersInRange(
Range(start: binaryColor.startIndex, end: binaryColor.startIndex.advancedBy(1)),
withString: "1")
Or simply
let resultString2 = binaryColor.stringByReplacingCharactersInRange(
binaryColor.startIndex..<binaryColor.startIndex.advancedBy(1),
withString: "1")
A: You have to set the variable:
var binaryColor: String = "000"
binaryColor = (binaryColor as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: "1")
println("This is binaryColor0: \(binaryColor)")
|
unknown
| |
d1143
|
train
|
Assuming I understood your question right that you want to fetch documents with a specific property value only if it exists, you can do something like this
var query = QueryBuilder.Select(SelectResult.expression(Meta.id),
SelectResult.expression(Expression.property("id")))
.From(DataSource.Database(db))
.Where(Expression.Property("name").NotNullOrMissing()
.And(Expression.Property("name").EqualTo(Expression.string("My first test"))))
Alternatively, if you know the Id of the document, it would be faster to do a GetDocument with the Id. Once you have the document, do a GetString on the name property. If it returns null, you can assume it does not exist.
Refer to the documentation on Couchbase Lite query fundamentals here.There are several examples. You may also want to check out API specs on NotNullOrMissing
|
unknown
| |
d1147
|
train
|
Define new command, my example is based on ForeColor:
(function(wysihtml5) {
wysihtml5.commands.setClass = {
exec: function(composer, command, element_class) {
element_class=element_class.split(/:/);
element=element_class[0];
newclass=element_class[1];
var REG_EXP = new RegExp(newclass,'g');
//register custom class
wysihtml5ParserRules['classes'][newclass]=1;
return wysihtml5.commands.formatInline.exec(composer, command, element, newclass, REG_EXP);
},
state: function(composer, command, element_class) {
element_class=element_class.split(/:/);
element=element_class[0];
newclass=element_class[1];
var REG_EXP = new RegExp(newclass,'g');
return wysihtml5.commands.formatInline.state(composer, command, element, newclass, REG_EXP);
}
};
})(wysihtml5);
usage:
HTML:
<div id="uxToolbar">
<button data-wysihtml5-command="setClass" data-wysihtml5-command-value="span:my-wysihtml5-custom-class" type="button" title="View HTML" tabindex="-1" class="btn btn-mini">
My class
</button>
</div>
so as you can see value is from two parts: element:class
DEMO
|
unknown
| |
d1151
|
train
|
The cross entropy is a way to compare two probability distributions. That is, it says how different or similar the two are. It is a mathematical function defined on two arrays or continuous distributions as shown here.
The 'sparse' part in 'sparse_categorical_crossentropy' indicates that the y_true value must have a single value per row, e.g. [0, 2, ...] that indicates which outcome (category) was the right choice. The model then outputs the y_pred that must be like [[.99, .01, 0], [.01, .5, .49], ...]. Here, model predicts that the 0th category has a chance of .99 in the first row. This is very close to the true value, that is [1,0,0]. The sparse_categorical_crossentropy would then calculate a single number with two distributions using the above mentioned formula and return that number.
If you used a 'categorical_crossentropy' it would expect the y_true to be a one-hot encoded vector, like [[0,0,1], [0,1,0], ...].
If you would like to know the details in depth, you can take a look at the source.
|
unknown
| |
d1157
|
train
|
These days the location of the emulated SD card is at /storage/emulated/0
A: On linux sdcard image is located in:
~/.android/avd/<avd name>.avd/sdcard.img
You can mount it for example with (assuming /mnt/sdcard is existing directory):
sudo mount sdcard.img -o loop /mnt/sdcard
To install apk file use adb:
adb install your_app.apk
A:
DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.
A: Drag & Drop
To install apk in avd, just manually drag and drop the apk file in the opened emulated device
The same if you want to copy a file to the sd card
A: if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command
adb install apklocation.apk
A: I have used the following procedure.
Android Studio 3.4.1
View>Tool Windows>Device File Explorer
A: *
*switch to DDMS perspective
*select the emulator in devices list, whose sdcard you want to explore.
*open File Explorer tab on right hand side.
*expand tree structure. mnt/sdcard/
refer to image below
To install apk manually:
copy your apk to to sdk/platform-tools folder and run following command in the same folder
adb install apklocation.apk
A: I have used the following procedure.
Procedure to install the apk files in Android Emulator(AVD):
Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder
Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.
Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools
*
*Go to Start -> Run -> cmd
*Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”
*Type adb install example.apk
*After getting success command
*Go to Application icon in Android emulator, we can see the your
application
A: //in linux
// in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img that is your sdcard file.
//To install apk in linux
$adb install ./yourfolder/myapkfile.apk
A: Adding to the usefile DDMS/File Explorer solution, for those that don't know, if you want to read a file you need to select the "Pull File from Device" button on the file viewer toolbar. Unfortunately you can't just drag out, or double click to read.
|
unknown
| |
d1161
|
train
|
What about:
ClassPathResource resource = new ClassPathResource("classpath:/sw/merlot/config/log4j.xml");
or if it is in a different jar file:
ClassPathResource resource = new ClassPathResource("classpath*:/sw/merlot/config/log4j.xml");
|
unknown
| |
d1167
|
train
|
I do not see any problem using @Asyncas this will release the request thread. But this is a simple approach and it has a lot of limitations. Note that if you want to deal with reactive streams, you do not have an API capable of that. For instance, if an @Async method calls another, the second will not be async.
The Webflux instead will bring the most complete API (in Java) to deal with things the reactive way. What you cannot do with only @Async. With Flux, for instance, you can process or access with multiple layers reactively and this you cannot reach the way you doing.
Nevertheless, it will bring a new universe for you, so if you just want to release the thread of the request, your approach is just fine, but if you need more you will have to deal with it in a more complex way.
Now, if you want to answer the HTTP request and then do the work asyncly, this is not what you want. I recommend that you have a JMS provider (like ActiveMQ), where your controller sends the message to be processed by a job and answers the request.
Hope it helps!
|
unknown
| |
d1169
|
train
|
See Textmate + RVM + Rake = Rake not using expected gem environment for some answers about this particular problem, and some advice on how to diagnose your own situation.
|
unknown
| |
d1171
|
train
|
Just change your query to this:
select
c.value('(../groupkey)[1]','int'),
c.value('(../groupname)[1]','nvarchar(max)'),
c.value('(contactkey)[1]','int'),
c.value('(contactname)[1]','nvarchar(max)')
from
@xml.nodes('contactdata/contacts/contact') as Contacts(c)
You need to get a list of all <contact> elements - and then extract that necessary data from those XML fragments. To get the groupkey and groupname, you can use the ../ to navigate "up the tree" one level to the parent node.
|
unknown
| |
d1173
|
train
|
Yes, you can include external files as part of your main body using \input. For example, assume you have mytable.table that contains
\begin{table}[ht]
\centering
\begin{tabular}{cc}
3 3
\end{tabular}
\caption{A table}\label{tab:mytable}
\end{table}
You can now use
\documentclass{article}
\begin{document}
Look at Table~\ref{tab:mytable}.
\input{mytable.table}
\end{document}
You wouldn't want to use \include here. See When should I use \input vs. \include?
|
unknown
| |
d1177
|
train
|
From Section 3.6.1 of http://smtlib.cs.uiowa.edu/papers/smt-lib-reference-v2.6-r2017-07-18.pdf:
Let. The let binder introduces and defines one or more local variables
in parallel. Semantically, a term of the form (let ((x1 t1) · · · (xn tn)) t) (3.3) is equivalent to the term t[t1/x1, . . . , tn/xn]
obtained from t by simultaneously replacing each free occurrence of xi
in t by ti , for each i = 1, . . . , n, possibly after a suitable
renaming of t’s bound variables to avoid capturing any variables in
t1, . . . , tn. Because of the parallel semantics, the variables x1, .
. . , xn in (3.3) must be pairwise distinct.
Remark 3 (No sequential
version of let). The language does not have a sequential version of
let. Its effect is achieved by nesting lets, as in (let ((x1 t1)) (let ((x2 t2)) t)).
As indicated in Remark 3, if you want to refer to an earlier definition you have to nest the let-expressions.
|
unknown
| |
d1179
|
train
|
You can use DatePipe API for this: https://angular.io/api/common/DatePipe
@Component({
selector: 'date-pipe',
template: `<div>
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'h:mm a z'}}</p> //format in this line
</div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
today: number = Date.now();
}
and this is what actually you want:
{{myDate | date: 'dd-MM-yyyy'}}
Edit: Using built-in pipe in component,
import { DatePipe } from '@angular/common';
class MyService {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
return this.datePipe.transform(date, 'yyyy-MM-dd');
}
}
Please read this topic, I took example from there: https://stackoverflow.com/a/35152297/5955138
Edit2:
As I described in comment, you can substring your date using this.
var str = '07112018'
var d = new Date(str.substring(0, 2)+'.'+str.substring(2, 4)+'.'+str.substring(4, 8));
Output: Wed Jul 11 2018 00:00:00 GMT+0300
A: try this function to convert time format as you require
timeFormetChange(){
var date =new Date();
var newDate = date.getDate();
var newMonth = date.getMonth();
var newYear =date.getFullYear();
var Hour = data.getHours();
var Minutes = data.getMinuets();
return `${newDate}-${newMonth }-${newYear} ${Hour}:${Minutes }`
}
|
unknown
| |
d1181
|
train
|
The API mentions Driver#quit as something to "quit the browser". It seems that adding @driver.quit to your rescue would do what you want.
|
unknown
| |
d1187
|
train
|
From the docs
unique:table,column,except,idColumn
The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.
Specifying A Custom Column Name:
'email' => 'unique:users,email_address'
You may need to specify the column to be checked against.
A: $feauturescheck= Feauture::where('Columname', '=',Input::get('input'))->count();
|
unknown
| |
d1189
|
train
|
Don't manually recurse if you can use standard tools. You can do this with sorting and grouping, but IMO preferrable is to use the types to express that you're building an associative result, i.e. a map from marks to students.
import qualified Data.Map as Map
splitToGroups :: [Student] -> Map.Map Mark [String]
splitToGroups students = Map.fromListWith (<>)
[ (sMark, [sName])
| Student sName sMark <- students ]
(If you want a list in the end, just use Map.toList.)
A: If you view Student as a tupple, your function has this type: splitToGroups :: [(Mark,String)] -> [(Mark, [String])].
So you need a function with type: [(a,b)] -> [(a,[b])].
Using Hoogle: search results
I get the following functions:
groupSort :: Ord k => [(k, v)] -> [(k, [v])]
collectSndByFst :: Ord a => [(a, b)] -> [(a, [b])]
They should solve your problem, remember to import the modules listed in the link to make them work. You should make a funtion that maps from Student -> (Mark, String) first.
|
unknown
| |
d1191
|
train
|
The DataContractJsonSerializer can handle JSON serialization but it's not as powerful as some of the libraries for example it has no Parse method.
This might be a way to do it without libraries as I beleive Mono has implemented this class.
To get more readable JSON markup your class with attributes:
[DataContract]
public class SomeJsonyThing
{
[DataMember(Name="my_element")]
public string MyElement { get; set; }
[DataMember(Name="my_nested_thing")]
public object MyNestedThing { get; set;}
}
A: Below is my implementation using the DataContractJsonSerializer. It works in mono 2.8 on windows and ubuntu 9.04 (with mono 2.8 built from source). (And, of course, it works in .NET!) I've implemented some suggestions from Best Practices: Data Contract Versioning
. The file is stored in the same folder as the exe (not sure if I did that in the best manner, but it works in win and linux).
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using NLog;
[DataContract]
public class UserSettings : IExtensibleDataObject
{
ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
[DataMember]
public int TestIntProp { get; set; }
private string _testStringField;
}
public static class SettingsManager
{
private static Logger _logger = LogManager.GetLogger("SettingsManager");
private static UserSettings _settings;
private static readonly string _path =
Path.Combine(
Path.GetDirectoryName(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName),
"settings.json");
public static UserSettings Settings
{
get
{
return _settings;
}
}
public static void Load()
{
if (string.IsNullOrEmpty(_path))
{
_logger.Trace("empty or null path");
_settings = new UserSettings();
}
else
{
try
{
using (var stream = File.OpenRead(_path))
{
_logger.Trace("opened file");
_settings = SerializationExtensions.LoadJson<UserSettings>(stream);
_logger.Trace("deserialized file ok");
}
}
catch (Exception e)
{
_logger.TraceException("exception", e);
if (e is InvalidCastException
|| e is FileNotFoundException
|| e is SerializationException
)
{
_settings = new UserSettings();
}
else
{
throw;
}
}
}
}
public static void Save()
{
if (File.Exists(_path))
{
string destFileName = _path + ".bak";
if (File.Exists(destFileName))
{
File.Delete(destFileName);
}
File.Move(_path, destFileName);
}
using (var stream = File.Open(_path, FileMode.Create))
{
Settings.WriteJson(stream);
}
}
}
public static class SerializationExtensions
{
public static T LoadJson<T>(Stream stream) where T : class
{
var serializer = new DataContractJsonSerializer(typeof(T));
object readObject = serializer.ReadObject(stream);
return (T)readObject;
}
public static void WriteJson<T>(this T value, Stream stream) where T : class
{
var serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(stream, value);
}
}
|
unknown
| |
d1193
|
train
|
You can have an autoscale group work across availability zones, but not across regions.
Though it is possible to have an ASG in a single AZ, you would certainly want the ASG to be in multiple AZ's, otherwise you have no real fault tolerance in the case where an AZ has problems.
|
unknown
| |
d1195
|
train
|
If all list items are integers, we can use clpfd!
:- use_module(library(clpfd)).
We define zmin_deleted/2 using maplist/2, (#=<)/2,
same_length/2, and select/3:
zmin_deleted(Zs1,Zs0) :-
same_length(Zs1,[_|Zs0]),
maplist(#=<(Min),Zs1),
select(Min,Zs1,Zs0).
Sample queries:
?- zmin_deleted([3,2,7,8],Zs).
Zs = [3,7,8]
; false.
?- zmin_deleted([3,2,7,8,2],Zs).
Zs = [3, 7,8,2]
; Zs = [3,2,7,8 ]
; false.
Note that zmin_deleted/2 also works in the "other direction":
?- zmin_deleted(Zs,[3,2,7,8]).
_A in inf..2, Zs = [_A, 3, 2, 7, 8]
; _A in inf..2, Zs = [ 3,_A, 2, 7, 8]
; _A in inf..2, Zs = [ 3, 2,_A, 7, 8]
; _A in inf..2, Zs = [ 3, 2, 7,_A, 8]
; _A in inf..2, Zs = [ 3, 2, 7, 8,_A]
; false.
A: Let me google it for you.
How could you find a minimum of a list..
Anyway, there is a nice min_list predicate.
?- min_list([1,2,2,3],X).
X = 1.
Here is a little example how could you remove some element from a list (notice, that all 2s is gone):
?- delete([1,2,2,3],2,X).
X = [1, 3].
If you wanna remove only first occasion of a element, use select:
?- select(2, [2,1,2,2,3], X), !.
X = [1, 2, 2, 3].
So your final answer could be something like that:
delete_min(A, C) :-
min_list(A, B),
select(B, A, C), !.
And
?- delete_min([1,1,2,3],X).
X = [1, 2, 3].
A: Again, just use the structural recursion on lists. Lists are built of nodes, [H|T], i.e. compound data structures with two fields - head, H, and tail, T. Head is the data (list element) held in the node, and T is the rest of the list.
We find minimum element by rolling along the list, while keeping an additional data - the minimum element from all seen so far:
minimum_elt([H|T],X):- minimum_elt(T,H,X).
There is no definition for the empty list case - empty lists do not have minimum elements.
minimum_elt([],X,X).
If there are no more elements in the list, the one we have so far is the answer.
minimum_elt([A|B],M,X):-
two cases here: A < M, or otherwise:
A < M, minimum_elt(B,A,X).
minimum_elt([A|B],M,X):-
A >= M, minimum_elt(B,M,X).
Nothing more to say about it, so this completes the program.
edit: except, you wanted to also delete that element. This changes things. Hmm. One obvious approach is first find the minimum elt, then delete it. We'll have to compare all elements once again, this time against the minimal element found previously. Can we do this in one scan?
In Lisp we could have. To remove any element from a list, surgically, we just reset the tail pointer of a previous node to point to the next node after the one being removed. Then using this approach, we'd scan the input list once, keeping the reference to the previous node to the minimum element found so far, swapping it as we find the smaller and smaller elements. Then when we've reached the end of the list, we'd just surgically remove the minimal node.
But in Prolog, we can't reset things. Prolog is a set once language. So looks like we're stuck with the need to pass over the list twice ... or we can try to be very smart about it, and construct all possible lists as we go, sorting them out each time we find the new candidate for the smallest element.
rem_min([A|B],L):-
% two possibilities: A is or isn't the minimum elt
rem_min(B,A,([A|Z],Z,Z),L).
rem_min([],A,(With,Without,Tail),L):- Tail = [],
% A is indeed the minimal element
L = Without.
rem_min([H|T],A,(With,Without,Tail),L):- H >= A, Tail=[H|Z],
rem_min(T,A,(With,Without,Z),L).
rem_min([H|T],A,(With,Without,Tail),L):- H < A, % use this H
copy_the_list(With,Tail,W2,T2), % no good - quadratic behaviour
Tail=[H|Z], T2=Z,
rem_min(T,A,(With,W2,Z),L).
copy_the_list([A|B],T,[A|C],C):- var(B), !, T=B. % fresh tail
copy_the_list([A|B],T,[A|C],T2):- copy_the_list(B,T,C,T2).
So looks like we can't avoid the second pass, but at least we can save all the superfluous comparisons:
rem_min([A|B],L):- N=[A|_], rem_min(B,A,N,[N|Z],Z,L).
rem_min([],_A,N,L2,Z,L):- Z=[], N=[_,1], % finalize the minimal entry
scan(L2,L).
rem_min([H|T],A,N,L2,Z,L):- H >= A, Z=[H|Z2], rem_min(T,A,N,L2,Z2,L).
rem_min([H|T],A,N,L2,Z,L):- H < A, % use this H
N2=[H|_], N=[_], % finalize the non-minimal entry
Z=[N2|Z2], rem_min(T,H,N2,L2,Z2,L).
scan( [], []).
scan( [[_,1]|B],C):- !, scan(B,C). % step over the minimal element
scan( [[A]|B],[A|C]):- !, scan(B,C). % previous candidate
scan( [A|B], [A|C]):- !, scan(B,C).
|
unknown
| |
d1205
|
train
|
You can use it like this
$array_holder = array("drilldown"=>$sImageUrl, "type"=>$Type, "job_no"=>$Job_No,"customer"=>$Customer);
$plates_data['data'][] = $array_holder;
|
unknown
| |
d1207
|
train
|
I assume that the class MyWeightedEdge already contains a method such as
public void setWeight(double weight)
If this is indeed the case, then what you need to do is:
Derive your own subclass from ListenableDirectedWeightedGraph (e.g., ListenableDirectedWeightedGraph). I would add both constructor versions, delegating to "super" to ensure compatibility with the original class.
Create the graph as in your question, but using the new class
ListenableDirectedWeightedGraph g =
new CustomListenableDirectedWeightedGraph(
MyWeightedEdge.class);
Override the method setEdgeWeight as follows:
public void setEdgeWeight(E e, double weight) {
super.setEdgeWeight(e, weight);
((MyWeightedEdge)e).setWeight(weight);
}
And, last but not least, override the toString method of the class MyWeightedEdge to return the label you want the edge to have (presumably including the weight, which is now available to it).
I hope this helps.
|
unknown
| |
d1209
|
train
|
Your source checks for a folder called myDir being created, but when you create new_file.txt, it isn't creating it in the myDir folder, it looks to be creating it in the externalDataDirectory folder.
So check the externalDataDirectory folder rather than your myDir folder, and you'll probably see your file there.
|
unknown
| |
d1213
|
train
|
Now it will work
word = gets.chomp
while word != ''
list = list.push word
word = gets.chomp
end
In your case, before pushing the first word to list( when you just entered into the while loop), you are calling again Kernel#gets and assigned it to word. That's why you lost the first word, and from that second one you started to pushing the words into the array.
A: Compare with functional approach:
sorted_words =
(1..Float::INFINITY)
.lazy
.map { gets.chomp }
.take_while { |word| !word.empty? }
.sort
A: You can make this cleaner if you realize that assignment returns the assigned value.
list = []
until (word = gets.chomp).empty? do
list << word
end
A: Here is another way your program can be rewritten, perhaps in a little more intuitive and expressive way:
word = 'word'
list = []
puts 'enter some words, man. ill tell em to you in alphabetical order.'
puts 'when your\'re done, just press enter without typing anything before.'
puts ''
keep_going = true
while keep_going
word = gets.chomp
keep_going = false if word.empty?
list = list.push word if keep_going
end
puts ''
puts 'Your alphabetically ordered words are:'
puts list.sort
puts ''
|
unknown
| |
d1215
|
train
|
While this is straight-forward in XSLT 2.0, in XSLT a two-pass transformation can produce the wanted results:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="kSolByVal" match="solution" use="."/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:variable name="vrtfPass1">
<xsl:apply-templates/>
</xsl:variable>
<xsl:apply-templates select=
"ext:node-set($vrtfPass1)
/*/*/*/*
/solutions/solution
[generate-id()
=
generate-id(key('kSolByVal', .)[1])
]"
mode="pass2"/>
</xsl:template>
<xsl:template mode="pass2" match="solution">
<div id="#{.}">
<xsl:apply-templates mode="pass2"
select="key('kSolByVal', .)/../../../.."/>
</div>
</xsl:template>
<xsl:template match="profile" mode="pass2">
<xsl:if test="position() = 1">
<xsl:text>
</xsl:text>
</xsl:if>
<xsl:value-of select=
"concat(customer, ', ', */summary, '
')"/>
</xsl:template>
<xsl:template match="solutions">
<solutions>
<xsl:apply-templates select="." mode="split"/>
</solutions>
</xsl:template>
<xsl:template match="solutions" name="split" mode="split">
<xsl:param name="pText" select="."/>
<xsl:if test="string-length($pText)">
<xsl:variable name="vText1"
select="concat($pText, ',')"/>
<xsl:variable name="vPart" select=
"substring-before($vText1, ',')"/>
<solution>
<xsl:value-of select="$vPart"/>
</solution>
<xsl:call-template name="split">
<xsl:with-param name="pText"
select="substring($pText, string-length($vPart)+2)"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided XML document (corrected for well-formedness):
<profiles>
<profile>
<customer>customer a </customer>
<collateral>
<summary>summary a</summary>
<related>
<solutions>sol1,sol2</solutions>
</related>
</collateral>
</profile>
<profile>
<customer>customer b </customer>
<collateral>
<summary>summary b</summary>
<related>
<solutions>sol1</solutions>
</related>
</collateral>
</profile>
<profile>
<customer>customer c </customer>
<collateral>
<summary>summary c</summary>
<related>
<solutions>sol2,sol3</solutions>
</related>
</collateral>
</profile>
</profiles>
the wanted, correct result is produced:
<div id="#sol1">
customer a , summary a
customer b , summary b
</div>
<div id="#sol2">
customer a , summary a
customer c , summary c
</div>
<div id="#sol3">
customer c , summary c
</div>
Explanation:
*
*We carry out the transformation in two passes. Pass2 is applied on the result of applying Pass1 on the provided XML document.
*Pass 1 is essentially the identity rule overriden for any solutions element. The processing of a solutions element consists in recursive splitting of its string value. The final result of Pass1 is the following:
--
<profiles>
<profile>
<customer>customer a </customer>
<collateral>
<summary>summary a</summary>
<related>
<solutions>
<solution>sol1</solution>
<solution>sol2</solution>
</solutions>
</related>
</collateral>
</profile>
<profile>
<customer>customer b </customer>
<collateral>
<summary>summary b</summary>
<related>
<solutions>
<solution>sol1</solution>
</solutions>
</related>
</collateral>
</profile>
<profile>
<customer>customer c </customer>
<collateral>
<summary>summary c</summary>
<related>
<solutions>
<solution>sol2</solution>
<solution>sol3</solution>
</solutions>
</related>
</collateral>
</profile>
</profiles>
.3. We then apply templates (in mode="pass2") on the result of Pass1. This is a typical and traditional Muenchian grouping.
|
unknown
| |
d1219
|
train
|
You can use parse_url to do the heavy lifting and then split the hostname by the dot, checking if the last two elements are the same:
$url1 = parse_url($url1);
$url2 = parse_url($url2);
$host_parts1 = explode(".", $url1["host"]);
$host_parts2 = explode(".", $url2["host"]);
if ($host_parts1[count($host_parts1)-1] == $host_parts2[count($host_parts2)-1] &&
($host_parts1[count($host_parts1)-2] == $host_parts2[count($host_parts2)-2]) {
echo "match";
} else {
echo "no match";
}
A: You could use parse_url for parsing the URL and get the root domain, like so:
*
*Add http:// to the URL if not already exists
*Get the hostname part of the URL using PHP_URL_HOST constant
*explode the URL by a dot (.)
*Get the last two chunks of the array using array_slice
*Implode the result array to get the root domain
A little function I made (which is a modified version of my own answer here):
function getRootDomain($url)
{
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
$domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
return $domain;
}
Test cases:
$a = 'http://example.com';
$urls = array(
'example.com/test',
'example.com/test.html',
'www.example.com/example.html',
'example.net/foobar',
'example.org/bar'
);
foreach ($urls as $url) {
if(getRootDomain($url) == getRootDomain($a)) {
echo "Root domain is the same\n";
}
else {
echo "Not same\n";
}
}
Output:
Root domain is the same
Root domain is the same
Root domain is the same
Not same
Not same
Note: This solution isn't foolproof and could fail for URLs like example.co.uk and you might want to additional checks to make sure that doesn't happen.
Demo!
A: I think that this answer can help: Searching partial strings PHP
Since these URLs are just strings anyway
|
unknown
| |
d1223
|
train
|
You probably haven't initialized either mapArray or moonGateArray thats why you are getting 0 count. In objective-c calling count on nil object doest not give any exception but instead returns 0.
hope that helps!
A: However for your count=0, this is straight forward you missed to alloc/init any of the array you used.
Are you creating a 2D array or 3D array?
It is creating confusion to get your logic?
Edit:
if your MAIN_APP is always 0, why you need an array, a simple object or instead of storing in 2D array you could have used dictionary. However the entire logic I can guess.
And I would like to add one more thing about your naming conventions... Name suffix or prefix your variable with Array, Button etc. you can use "maps", "moonGates", all plural symbolizes its gonna to be an array.
A: Most likely you haven't properly initialize your arrays. Make your like easier and change your code a bit to make it easier to read and easier to debug. You don't get points for writing highly nested method calls. It makes your life harder. Split the code up to make things easier.
Change this:
for (int i = 0; i < 8; i++) {
[[[mapArray objectAtIndex:MAIN_MAP] moonGateArray] addObject:[Moongate new]];
}
to this:
// replace "SomeMapClass" with your actual class name
SomeMapClass *mainMap = mapArray[MAIN_MAP];
NSMutableArray *moonArray = mainMap.moonGateArray;
for (int i = 0; i < 8; i++) {
[moonArray addObject:[Moongate new]];
}
Now you can run this code in the debugger or add NSLog statements and verify each step of the process.
Is mapArray properly initialized?
Is moonArray property initialized?
Remember, simply defining a property doesn't actually create the object. You still need to initialize it.
|
unknown
| |
d1225
|
train
|
Consider the following code snippet to dynamically change tables:
var mainList = [{tableId:1}, {tableId:2}, {tableId:3}]
function mainController(){
var vm = this;
vm.mainList = mainList;
vm.currentIndex = 0;
vm.currentTable = currentTable();
function showNext(){
vm.currentIndex++;
vm.currentTable = currentTable();
}
function currentTable(){
return vm.mainList[currentIndex];
}
}
<div tableId="{{'table'+currentTable.tableId}}" >
<table class="animate-if">
<thead>
<tr>
<th>Names</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=" one in currentTable | limitTo: 4 ">
<td>{{one.name}}</td>
<td>{{one.address}}</td>
</tr>
</tbody>
</table>
</div>
Next
If you really need to have ng-repeat of all available tables and show/hide tables on next press than modify code in such way:
var mainList = [{tableId:1}, {tableId:2}, {tableId:3}]
function mainController(){
var vm = this;
vm.mainList = mainList;
vm.currentIndex = 0;
vm.currentTable = currentTable();
function showNext(){
vm.currentIndex++;
vm.currentTable = currentTable();
}
function currentTable(){
return vm.mainList[currentIndex];
}
function isActive(table){
var tableIndex = mainList.indexOf(table);
return tableIndex === currentIndex;
}
}
<div tableId="{{'table'+currentTable.tableId}}" ng-repeat="table in
mainList"
ng-if="isActive(table)">
<table class="animate-if">
<thead>
<tr>
<th>Names</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=" one in currentTable | limitTo: 4 ">
<td>{{one.name}}</td>
<td>{{one.address}}</td>
</tr>
</tbody>
</table>
</div>
<button class="btn " ng-click="showNext() "> Next </button>
A: Replace the below code with your appropriate data structures since it is unclear from question.
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.mainList=[[{name:"dummy1"},{name:"dummy2"}],[{name:"dummy3"},{name:"dummy4"}]];
$scope.count=1;
$scope.showNext = function () {
$scope.count=$scope.count+1;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="oneList in mainList | limitTo: count ">
<table class="animate-if">
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="one in oneList | limitTo: 4 ">
<td>{{one.name}}</td>
</tr>
</tbody>
</table>
</div>
<button class="btn" ng-click="showNext()"> Next </button>
</div>
A: After some workaround I found the answer what I was looking for.
Thanks to @Ihor Korotenko.
One modification in html file is "ng-show" attribute.
<div ng-init="outerIndex=($index)" tableId="{{'table'+outerIndex}}" ng-repeat="oneList in mainList" ng-show="oneList.flagValue">
<table class="animate-if">
<thead>
<tr>
<th>Names</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=" one in oneList | limitTo: 4 ">
<td>{{one.name}}</td>
<td>{{one.address}}</td>
</tr>
</tbody>
</table>
</div>
<button class="btn " ng-click="more()"> More </button>
<button class="btn " ng-click="less()"> Less </button>
Now here is the jQuery code:
$scope.getValueFromSvc= function ($index) {
Service.myMethod().then(function (response) {
var total = response.responseData;
var mainList= []; // contains all oneList
var oneList = []; //contain one table
$.each(total, function (i, value){
// iterate data here to put in oneList then mainList
}
});
// assigning flag which will be helpful on applying condition in next jQuery segment
$.each(mainList, function (i, value) {
if (i == 0)
value.flagValue = true;
else
value.flagValue = false;
});
$scope.mainList = mainList;
});
}
And finally to show table on button click jQuery goes like...
$scope.more = function () {
$.each($scope.mainList, function (i, value) {
if (!value.flagValue) {
value.flagValue = true;
return false;
}
});
};
$scope.less = function () {
for (var v = $scope.mainList.length - 1; v > 0; v--){
if ($scope.mainList[v].flagValue) {
$scope.mainList[v].flagValue = false;
break;
}
}
};
|
unknown
| |
d1227
|
train
|
Z") ' Define your own range here
If strPattern <> "" Then ' If the cell is not empty
If regEx.Test(Cell.Value) Then ' Check if there is a match
Cell.Interior.ColorIndex = 6 ' If yes, change the background color
End If
End If
Next
A: I have made the Changes.
*
*Use Find function to locate the column. used cnum for that
*Use Worksheets("Consolidated") without the .
*Pass the column number found to the loop range
Dim strPattern As String: strPattern = "[^a-z0-9-]"
Dim regEx As Object
Dim Cell As Range
Dim cnum As Integer
Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True
regEx.Pattern = strPattern
cnum = Worksheets("Consolidated").Range("A1:Z1").Find("First Name").Column 'column number to search in
For Each Cell In Worksheets("Consolidated").Range(Cells(2, cnum), Cells(1000, cnum))
If strPattern <> "" Then ' If the cell is not empty
If regEx.Test(Cell.Value) Then ' Check if there is a match
Cell.Interior.ColorIndex = 6 ' If yes, change the background color
End If
End If
Next
|
unknown
| |
d1229
|
train
|
Off the top of my head...
If the determinant is 0 then the matrix cannot be inverted, which can be useful to know.
If the determinant is negative, then objects transformed by the matrix will reversed as if in a mirror (left handedness becomes right handedness and vice-versa)
For 3x3 matrices, the volume of an object will be multiplied by the determinant when it is transformed by the matrix. Knowing this could be useful for determining, for example, the level of detail / number of polygons to use when rendering an object.
A: In 3D vector graphics
there are used 4x4 homogenuous transform matrices and we need booth direct and inverse matrices which can be computed by (sub)determinants. But for orthogonal matrices there are faster and more accurate methods like
*
*full pseudo inverse matrix.
Many intersection tests use determinants (or can be converted to use them) especially for quadratic equations (ellipsoids,...) for example:
*
*ray and ellipsoid intersection accuracy improvement
as Matt Timmermans suggested you can decide if your matrix is invertible or left/right handed which is useful to detect errors in matrices (accuracy degradation) or porting skeletons in between formats or engines etc.
And I am sure there area lot of other uses for it in vector math (IIRC IGES use them for rotational surfaces, cross product is determinant,...)
A: The incircle test is a key primitive for computing Voronoi diagrams and Delaunay triangulations. It is given by the sign of a 4x4 determinant.
(picture from https://www.cs.cmu.edu/~quake/robust.html)
|
unknown
| |
d1233
|
train
|
You have not specified the size of the data member of struct scs_data_tag. This declares a C99 flexible array member. This member has size 0 by default, and you'd need to malloc more than the actual struct size in order for it to be able to contain data.
According to the standard, it should not be possible for struct scs_data_tag to be an element of an array (because it contains a flexible array member). But this is supported by some compilers as an extension.
If you instead give this array a large enough size (e.g. char data[40]), your code should work.
A: Adding to interjay's answer,. You see adsafe_tags[1].key_size = 11888 which is 0x2e70 in hex, which denotes ASCII characters p (= 0x70) and . (= 0x2e), therefore "p.".
Similarly, adsafe_tags[1].val_size = 29537, which is 0x7361 or "as", rest is printed correctly as a string.
This shows that no space is allocated to adsafe_tags[0].data.
The string you provided for initializing it got mapped to next data set.
|
unknown
| |
d1237
|
train
|
So the way the new embedded DNS "server" works is that it isn't a formal server. It's just an embedded listener for traffic to 127.0.0.11:53 (udp of course). When docker sees that query traffic on the container's network interface, it steps in with its embedded DNS server and replies with any answers it might have to the query. The documentation has some options you can set to affect how this DNS server behaves, but since it only listens for query traffic on that localhost address, there is no way to expose this to an overlay network in the way that you are thinking. However this seems to be a moving target, and I have seen this question before in IRC, so it may one day be the case that this embedded DNS server at least becomes pluggable, or possibly exposable in the way you would like.
|
unknown
| |
d1243
|
train
|
Assuming eventtimes is a cell array of strings, you can do this:
eventtimes={'0h 0m 19.72s'
'0h 1m 46s'
'0h 6m 45.9s'
'0h 6m 53.18s'};
for i=1:length(eventtimes)
%// Read each line of data individually
M(i,:)=sscanf(eventtimes{i},'%d%*s%d%*s%f%*s').';
end
s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds
which gives
s =
19.7200
106.0000
405.9000
413.1800
A: With respect to the answer provided by @David, the last line of code:
s=(M(:,1)*24+M(:,2))*60+M(:,3) %// Convert into seconds
should be:
s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds
Since M(:,1) contains hours, to convert them into seconds, they have to be multiplied by 3600 (60 min. * 60 sec.)
The expected resuls as described in the question and the ones provided by @David seem correct only because all input have "0h".
In case any of the input times last more than 1h, the results will be:
0h 0m 19.72s
2h 1m 46s
3h 6m 45.9s
0h 6m 53.18s
s=
19.72
7306.00
11205.90
413.18
Hope this helps.
A: I've found a solution using etime that bypasses the "between" function and its odd calendarDuration type output:
%read in with fractions
times=datetime(myCellArray(:,1),'InputFormat','HH:mm:ss.SS');
%turn into datevectors (uses today's date: works as long as midnight isn't crossed)
timevect=datevec(times);
%separate start time from subsequent times
starttime=timevect(1,:);
othertimes=timevect(2:end,:);
%use etime with repmat of starttime to get differences:
relativetimes=etime(othertimes,repmat(starttime,[size(othertimes,1) 1]));
relativetimes(1:4)
ans =
19.72
106
405.9
413.18
|
unknown
| |
d1247
|
train
|
auth = str(base64.b64encode(bytes(f'{self.user}:{self.password}', "utf-8")), "ascii").strip()
You may not be using the f-string correctly, change f'{self.user, self.password}' to f'{self.user}:{self.password}'
More info
|
unknown
| |
d1249
|
train
|
You should be updating the underlying dataset that is passed to the adapter before calling notifyDatasetChanged();
EG:
For ArrayAdapter in a ListActivity
("arraylist" is the ArrayList you've used to back your ArrayAdapter)
arraylist.add(data);
arrayadapter = this.getListAdapter();
arrayadapter.notifyDatasetChanged();
A: Personally, everytime user like press refresh button i repopulate listView initializing Cursor again.
Like this: calling this function...
public void repopulateListView(){
cursor = dbHelper.fetchAll();
columns = new String[] {
DBAdapter.KEY_NAME,
DBAdapter.KEY_DATE,
DBAdapter.KEY_VOTE,
DBAdapter.KEY_CREDIT
};
to = new int[] {
R.id.one,
R.id.two,
R.id.three,
R.id.four
};
dataAdapter = new SimpleCursorAdapter(
getActivity(), R.layout.YOUR_ID,
cursor,
columns,
to,
0)
{
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
final View row = super.getView(position, convertView, parent);
}
}
}
...from Refresh onClick:
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.refresh:{
repopulateListView();
break;
}
}
}
|
unknown
| |
d1251
|
train
|
You must use the capistrano/bundler gem to get the bundler tasks (like bundle install) in your deploy.
Basically, you must add the capistrano/bundler in your Gemfile and require it in your Capfile using the command below:
require 'capistrano/bundler'
Thereby the Capistrano will run the bundle install task during the deploy and this problem will be solved.
|
unknown
| |
d1253
|
train
|
Edit: This issue was fixed by this PR which appears to have first landed in Flutter 1.22.0.
It took some sleuthing, but I eventually found the mechanism for this behavior.
TextField wraps EditableText. When the latter gains focus, it will invoke _showCaretOnScreen, which includes a call to renderEditable.showOnScreen. This bubbles up and eventually causes the scrolling behavior.
We can force _showCaretOnScreen to return early here if we supply to the TextField a hacked ScrollController that always returns false from hasClients:
class _HackScrollController extends ScrollController {
// Causes early return from EditableText._showCaretOnScreen, preventing focus
// gain from making the CustomScrollView jump to the top.
@override
bool get hasClients => false;
}
The behavior does not seem intentional, so I reported it as bug #60422.
Caveats
This workaround may not be very stable.
I don't know what adverse effects the hasClients override might have.
The docs for TextField say that the scrollController is used "when vertically scrolling the input". In this use case we don't want vertical scrolling anyway, so the workaround might not cause any problems. In my brief testing it didn't seem to cause problems with horizontal (overflow) scrolling.
A: Just like the documentation mentions try and use resizeToAvoidBottomInset parameter to false (defaults to true) in the scaffold widget https://api.flutter.dev/flutter/material/Scaffold/resizeToAvoidBottomInset.html
Also I would recommend creating ValueListenableBuilder after the scaffold (as the first widget in the body) to avoid rebuilding the whole scaffold and just the body widget
|
unknown
| |
d1255
|
train
|
Moving declaration of case class out of scope did the trick!
Code structure will then be like:
package main.scala.UserAnalytics
// case class *outside* the main object
case class User(name: string, dept: String)
object UserAnalytics extends App {
...
ds = df.map { row => User(row.getString(0), row.getString(1)) }
}
|
unknown
| |
d1261
|
train
|
I see 2 options here:
*
*You have a break that gets executed where it is says My code with conditions here.
*rp doesn't return a Promise.
As for the second option, here's a quick code to show you that the final line of an async function gets executed only when all awaits are finished:
const delay = (ms) => {
return new Promise(r => {
setTimeout(r, ms);
console.log("delayed", ms);
});
}
const run = async () => {
for (var i = 0; i < 3; i++) {
await delay(1000);
}
console.log("finished");
}
run();
|
unknown
| |
d1263
|
train
|
try:
function goto() {
document.getElementById("iframe").src = document.getElementById('webLinks').options[document.getElementById('webLinks').selectedIndex].text;
}
A: you have a js error, edit following function
function goto() {
document.getElementById("iframe").src = document.getElementsByTagName("option")[1].value;
}
or common approach
function goto() {
document.getElementById("iframe").src = document.getElementById('webLinks').options[document.getElementById('webLinks').selectedIndex].text;
}
|
unknown
| |
d1267
|
train
|
You need to change that condition to only execute the code if it matches the cell address, rather than not execute the code unless the address is matched. This will allow you to add further conditions matched on cell address.
I'd recommend changing a hard-coded cell address like "$C$37" to a named range and that named range should ideally be unique throughout the workbook.
arCases = Array("Term", "Indeterminate", "Transfer", "Student", "Term extension", "As required", "Assignment", "Indéterminé", "Mutation", "Selon le besoin", "Terme", "prolongation du terme", "affectation", "Étudiant(e)")
If Target.Address = "$C$37" Then
res = Application.Match(Target, arCases, 0)
If IsError(res) Then
Rows("104:112").Hidden = False
Else
Rows("104:112").Hidden = True
End If
ElseIf Target.Address = "$H$4" Then
' Do something else
End If
End Sub
|
unknown
| |
d1269
|
train
|
Try:
Example1
String[] separated = CurrentString.split("am");
separated[0]; // I am
separated[1]; // Vahid
Example2
StringTokenizer tokens = new StringTokenizer(CurrentString, "am");
String first = tokens.nextToken();// I am
String second = tokens.nextToken(); //Vahid
A: Try:
String text = "I am Vahid";
String after = "am";
int index = text.indexOf(after);
String result = "";
if(index != -1){
result = text.substring(index + after.length());
}
System.out.print(result);
A: Just use like this, call the method with your string.
public String trimString(String stringyouwanttoTrim)
{
if(stringyouwanttoTrim.contains("I am")
{
return stringyouwanttoTrim.split("I am")[1].trim();
}
else
{
return stringyouwanttoTrim;
}
}
A: If you prefer to split your sentence by blank space you could do like this :
String [] myStringElements = "I am Vahid".split(" ");
System.out.println("your name is " + myStringElements[myStringElements.length - 1]);
|
unknown
| |
d1273
|
train
|
For me, the fix was to switch to the 32 bit version of InternetExplorerDriver.exe from https://code.google.com/p/selenium/downloads/list
Seemingly named IEDriverServer nowadays, but works if you just rename it to InternetExplorerDriver.exe.
A: Using the C#, NUnit, C# webdriver client and IEDriverServer, I originally had the problem with slow input (e.g., sending keys to an input box would take about 5 seconds between keys, or clicking on a button same kind of delay).
Then, after reading this thread, I switched to the 32-bit IEDriverServer, and that seemed to solve the problem.
But today I was experimenting with the InternetExplorerOptions object in order to set some options on IE according to this documentation:
https://code.google.com/p/selenium/wiki/InternetExplorerDriver
Per the documentation, I created the registry value HKCU\Software\Microsoft\Internet Explorer\Main\TabProcGrowth with a value of 0 in order to use ForceCreateProcessApi = true and BrowserCommandLineArguments = "-private."
After doing this, I noticed that the slow-input problem was back. I had made several changes to my code, but after rolling all of them back, the problem still persisted. When I removed the aforementioned registry key, however, the input was back to full speed (no delay).
A: check 'prefer 32 bit' is not checked in your build properties. If it is and you are using the 64 bit IE driver it will run like an asthmatic snail.
|
unknown
| |
d1275
|
train
|
if(splitMessage[0] === '!cmd'){
var c = message.content.split(/ (.+)/)[1];
try {
eval(c);
} catch (err) {
console.log('There is an error!')
}
}
Modifying a code in runtime is so bad though.
|
unknown
| |
d1277
|
train
|
Probably the debug_print_backtrace() from PHP can help you.
These way you can see all the functions that have been called.
More details: http://php.net/manual/en/function.debug-print-backtrace.php
|
unknown
| |
d1287
|
train
|
Maybe it is possible to do something via .inherited and .undef_method, isn't it?
Yes, it is possible. But the idea smells, as for me - you're going to break substitutability.
If you don't want the "derived" classes to inherit the behavior of the parent, why do you use inheritance at all? Try composition instead and mix in only the behavior you need. For example, something like this could work (very dirty example, but I hope you got the idea):
class A
module Registry
def register_as(name)
A.register_as(name, self)
end
end
@registered = {}
def self.register_as(name, klass)
@registered[name] = klass
end
def self.known
@registered
end
end
class B
extend A::Registry
register_as :b
end
class C
extend A::Registry
register_as :c
end
A.known # => {:b => B, :c => C}
|
unknown
| |
d1291
|
train
|
The problem is that you are calling an instance of class Window but not ComboBox. I see to possible reasons why this happens. Either you are referring to the wrong ui property from UIMap or Coded UI Test Builder recorded wrong element or not the whole hierarchy of your wanted test control.
Moreover, if you are trying to select an item in combobox, then just use
comboBox.SelectedIndex = 3; // to select an item by its zero-based index
comboBox.SelectedItem = "Item Text"; // to select an item by its text
If it does not help, provide additional information on the problem, particularly on the technology of your Windows Application (UIA/WPF or MSAA/WinForms).
|
unknown
| |
d1293
|
train
|
I can't reproduce the problem:
File: /path/to/file/data.csv
ZwpBHCrWObHE61rSOpp9dkUfJ, '{"bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}, "models": {"Grand Cherokee": 1, "XC90": 1}}', '{"bodystyle": "SUV/MUV", "budgetsegment": "EP", "models": "Grand Cherokee,XC90"}'
MySQL Command Line:
mysql> \! lsb_release --description
Description: Ubuntu 16.04.2 LTS
mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.19 |
+-----------+
1 row in set (0.00 sec)
mysql> DROP TABLE IF EXISTS `table`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `table` (
-> `cookie` VARCHAR(25) NOT NULL,
-> `userdata` JSON NOT NULL,
-> `userprefernce` JSON NOT NULL
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> LOAD DATA LOCAL INFILE '/path/to/file/data.csv'
-> INTO TABLE `table`
-> FIELDS TERMINATED BY ', '
-> OPTIONALLY ENCLOSED BY '\''
-> LINES TERMINATED BY '\n';
Query OK, 1 row affected (0.00 sec)
Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
mysql> SELECT
-> `cookie`,
-> `userdata`,
-> `userprefernce`
-> FROM
-> `table`\G
*************************** 1. row ***************************
cookie: ZwpBHCrWObHE61rSOpp9dkUfJ
userdata: {"models": {"XC90": 1, "Grand Cherokee": 1}, "bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}}
userprefernce: {"models": "Grand Cherokee,XC90", "bodystyle": "SUV/MUV", "budgetsegment": "EP"}
1 row in set (0.00 sec)
|
unknown
| |
d1297
|
train
|
Your type can be defined in a simpler way, you don't need slist:
type 'a sexp = Symbol of 'a | L of 'a sexp list
Your problem is that subst a b S[q] is read as subst a b S [q], that is the function subst applied to 4 arguments. You must write subst a b (S[q]) instead.
|
unknown
| |
d1301
|
train
|
Why do you think you need the cast? If it is a collection of A * you should just be able to say:
(*begin)->doIt();
A: You can use the std::foreach for that:
std::for_each( v.begin(), v.end(), std::mem_fun( &A::doIt ) );
The std::mem_fun will create an object that calls the given member function for it's operator() argument. The for_each will call this object for every element within v.begin() and v.end().
A: You should provide error messages to get better answers.
In your code, the first thing that comes to mind is to use
elem->doIt();
What is the "serializable" type ?
|
unknown
| |
d1303
|
train
|
It doesn't work that way. The service is only accessible via DNS, not IP address.
Upgrading from Standard tier to Premium gives you throughput and latency commitment, but not an IP address.
|
unknown
| |
d1305
|
train
|
Use this to redirect all traffic to new site using .htaccess of old sites.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} .*hemodialysis-krk.com
RewriteRule (.*) http://www.newsite.com/ [R=301,L]
</IfModule>
Or create more rules, if you can map sections of pages from old to new site. If you use:
RewriteRule (.*) http://www.newsite.com/$1 [R=301,QSA,L]
original path and get query will be used in redirection too. This is always handy working on unique url to reach better position in search engines results.
EDIT:
If you need to redirect only urls, which don't exists anymore, then use (not tested):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) / [R=301,L]
</IfModule>
|
unknown
| |
d1307
|
train
|
It seems as though the only additional resources you're provided with have to do with screen density and resolution: http://developer.android.com/guide/webapps/index.html. However, if you are going to display this page in a WebView, you can utilize the Java-Javascript bridge to access any information available to the standard Java API (or non standard if you want to get creative and use reflection ;-) )
A: Edit: Oops, didn't see you meant from the browser javascript >< disregard information below.
android.os.Build provides a lot of information.
Try:
String s="Debug-infos:";
s += "\n OS Version: " + System.getProperty("os.version") + "(" + android.os.Build.VERSION.INCREMENTAL + ")";
s += "\n OS API Level: " + android.os.Build.VERSION.SDK;
s += "\n Device: " + android.os.Build.DEVICE;
s += "\n Model (and Product): " + android.os.Build.MODEL + " ("+ android.os.Build.PRODUCT + ")";
|
unknown
| |
d1309
|
train
|
You need to activate the wrap on the parent element (the flex container) then make the element full width:
.main{
display:flex;
border: 1px solid black;
flex-wrap:wrap;
}
.item, .item2, .item3, .item4{
padding: 10px;
}
.item {
flex-grow: 1;
}
.item2{
flex-grow: 7;
background-color: pink;
}
.item3 {
flex-grow: 2;
background-color: yellow;
}
.item4 {
flex-basis:100%;
}
<div class="main">
<div class="item">1</div>
<div class="item2">2</div>
<div class="item3">3</div>
<div class="item4">4</div>
</div>
A: Use .item-groups to organize your .items by row. Example:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.main {
display: flex;
border: 1px solid black;
flex-wrap: wrap;
}
.item-group {
flex-basis: 100%;
display: flex;
}
.item1, .item2, .item3, .item4 {
padding: 10px;
}
.item1 {
flex-grow: 1;
}
.item2{
flex-grow: 7;
background-color: pink;
}
.item3 {
flex-grow: 2;
background-color: yellow;
}
.item4 {
background-color: violet;
}
<div class="main">
<div class="item-group">
<div class="item1">1</div>
<div class="item2">2</div>
<div class="item3">3</div>
</div>
<div class="item-group">
<div class="item4">4</div>
</div>
</div>
|
unknown
| |
d1313
|
train
|
I think this should help
substr(x, str_locate(x, "?")+1, nchar(x))
A: Try this:
sub('.*\\?(.*)','\\1',x)
A: x <- "Name of the Student? Michael Sneider"
sub(pattern = ".+?\\?" , x , replacement = '' )
A: To take advantage of the loose wording of the question, we can go WAY overboard and use natural language processing to extract all names from the string:
library(openNLP)
library(NLP)
# you'll also have to install the models with the next line, if you haven't already
# install.packages('openNLPmodels.en', repos = 'http://datacube.wu.ac.at/', type = 'source')
s <- as.String(x) # convert x to NLP package's String object
# make annotators
sent_token_annotator <- Maxent_Sent_Token_Annotator()
word_token_annotator <- Maxent_Word_Token_Annotator()
entity_annotator <- Maxent_Entity_Annotator()
# call sentence and word annotators
s_annotated <- annotate(s, list(sent_token_annotator, word_token_annotator))
# call entity annotator (which defaults to "person") and subset the string
s[entity_annotator(s, s_annotated)]
## Michael Sneider
Overkill? Probably. But interesting, and not actually all that hard to implement, really.
A: str_match is more helpful in this situation
str_match(x, ".*\\?\\s(.*)")[, 2]
#[1] "Michael Sneider"
|
unknown
| |
d1315
|
train
|
Did you tried to clone it ?
git clone -b 4.17-arcore-sdk-preview https://github.com/google-ar-unreal/UnrealEngine.git
A: That repository is actually private. So you cannot access/clone it. What you can do is fork the repository on the link you provided and then clone your fork.
Edit
So the guide here at time of writing is incorrect.
You have to follow the steps to become part of the Epic Organisation on github. When you follow these steps you'll see a private repos which you need to fork.
TL;DR: The clone command in the guide doesn't work now because the repository is private. Forking it works after become part of Epic organisation @ Github!
|
unknown
| |
d1317
|
train
|
Posted something very similar to this yesterday. As you know, you can only perform such function with dynamic sql.
Now, I don't have your functions, so you will have to supply those.
I've done something very similar in the past to calculate a series of ratios in one pass for numerous income/balance sheets
Below is one approach. (However, I'm not digging the 2 parameters ... seems a little limited, but I'm sure you can expand as necessary)
Declare @Formula table (ID int,Title varchar(25),Formula varchar(max))
Insert Into @Formula values
(1,'Sum' ,'@a+@b')
,(2,'Multiply','@a*@b')
Declare @Parameter table (a varchar(50),b varchar(50))
Insert Into @Parameter values
(1,2),
(5,3)
Declare @SQL varchar(max)=''
;with cte as (
Select A.ID
,A.Title
,ParameterA = A
,ParameterB = B
,Expression = Replace(Replace(Formula,'@a',a),'@b',b)
From @Formula A
Cross Join @Parameter B
)
Select @SQL = @SQL+concat(',(',ID,',',ParameterA,',',ParameterB,',''',Title,''',(',Expression,'))') From cte
Select @SQL = 'Select * From ('+Stuff(@SQL,1,1,'values')+') N(ID,ParameterA,ParameterB,Title,Value)'
Exec(@SQL)
-- Optional To Trap Results in a Table Variable
--Declare @Results table (ID int,ParameterA varchar(50),ParameterB varchar(50),Title varchar(50),Value float)
--Insert Into @Results Exec(@SQL)
--Select * from @Results
Returns
ID ParameterA ParameterB Title Value
1 1 2 Sum 3
2 1 2 Multiply 2
1 5 3 Sum 8
2 5 3 Multiply 15
|
unknown
| |
d1321
|
train
|
If the only things your don't want comma-separated are strings that have years in, use:
knit_hooks$set(inline = function(x) {
if(is.numeric(x)){
return(prettyNum(x, big.mark=","))
}else{
return(x)
}
})
That works for your calendar string. But suppose you want to just print a year number on its own? Well, how about using the above hook and converting to character:
What about \Sexpr{2014}? % gets commad
What about \Sexpr{as.character(2014)}? % not commad
or possibly (untested):
What about \Sexpr{paste(2014)}? % not commad
which converts the scalar to character and saves a bit of typing. We're not playing code golf here though...
Alternatively a class-based method:
comma <- function(x){structure(x,class="comma")}
nocomma <- function(x){structure(x,class="nocomma")}
options(scipen=999) # turn off scientific notation for numbers
opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE)
knit_hooks$set(inline = function(x) {
if(inherits(x,"comma")) return(prettyNum(x, big.mark=","))
if(inherits(x,"nocomma")) return(x)
return(x) # default
})
wantcomma <- 1234*5
nocomma1 <- "September 1, 2014" # note name change here to not clash with function
Then just wrap your Sexpr in either comma or nocomma like:
The hook will separate \Sexpr{comma(wantcomma)} and \Sexpr{nocomma(nocomma1)}, but I don't want to separate years.
If you want the default to commaify then change the line commented "# default" to use prettyNum. Although I'm thinking I've overcomplicated this and the comma and nocomma functions could just compute the string format themselves and then you wouldn't need a hook at all.
Without knowing exactly your cases I don't think we can write a function that infers the comma-sep scheme - for example it would have to know that "1342 cases in 2013" needs its first number commad and not its second...
|
unknown
| |
d1323
|
train
|
Stripe has a guide to upgrading or downgrading Subscriptions that covers what you're asking about.
The high-level steps are:
*
*Create a new Price representing the new billing period under the Product you already have
*Update the Subscription using the new Price
|
unknown
| |
d1325
|
train
|
Response is correct. I've tried requesting the website (the real one) and it works:
print(response.data.base64EncodedString())
If you decode the BASE64 data, it will render valid HTML code.
The issue seems related to encoding. After checking the website's head tag, it states that the charset is windows-1254
String(data: response.data, encoding: .windowsCP1254) // works. latin1, etc.
Your issue is similar to SWIFT: NSURLSession convert data to String
|
unknown
| |
d1327
|
train
|
From the question, it would seem that the background job does not modify state of database.
Simplest way to avoid performance hit on main application, while there is a background job running, is to take database dump and perform analysis on that dump.
|
unknown
| |
d1331
|
train
|
I think there are two things to you think about:
*
*if you want to use redis with django celery (Celery beat).
*if you want to use just redis as M.Q with django.
Below are the references to help you with each case:
For Case 1: check out the link below
*
*https://enlear.academy/hands-on-with-redis-and-django-ed7df9104343
For Case 2: check out the link below
*How can I publish a message in Redis channel asynchronously with python?
(I recommand this one best : https://stackabuse.com/working-with-redis-in-python-with-django/) -- it covers all you need about using redis for caching
|
unknown
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.