id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44,272,914 | Sharing data between fragments using new architecture component ViewModel | <p>On Last Google IO, Google released a preview of some new arch components, one of which, ViewModel.</p>
<p>In the <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing_data_between_fragments" rel="noreferrer">docs</a> google shows one of the possible uses for this component:</p>
<blockquote>
<p>It is very common that two or more fragments in an activity need to
communicate with each other. This is never trivial as both fragments
need to define some interface description, and the owner activity must
bind the two together. Moreover, both fragments must handle the case
where the other fragment is not yet created or not visible.</p>
<p>This common pain point can be addressed by using ViewModel objects.
Imagine a common case of master-detail fragments, where we have a
fragment in which the user selects an item from a list and another
fragment that displays the contents of the selected item.</p>
<p>These fragments can share a ViewModel using their activity scope to
handle this communication.</p>
</blockquote>
<p>And shows a implementation example:</p>
<pre><code>public class SharedViewModel extends ViewModel {
private final SavedStateHandle state;
public SharedViewModel(SavedStateHandle state) {
this.state = state;
}
private final MutableLiveData<Item> selected = state.getLiveData("selected");
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
@Override
protected void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
model = new ViewModelProvider(getActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
@Override
protected void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedViewModel model = new ViewModelProvider(getActivity()).get(SharedViewModel.class);
model.getSelected().observe(this, { item ->
// update UI
});
}
}
</code></pre>
<p>I was quite excited about the possibility of not needing those interfaces used for fragments to communicate through the activity.</p>
<p>But Google's example does not show exactly how would I call the detail fragment from master.</p>
<p>I'd still have to use <a href="https://developer.android.com/training/basics/fragments/communicating.html" rel="noreferrer">an interface</a> that will be implemented by the activity, which will call fragmentManager.replace(...), or there is another way to do that using the new architecture?</p> | 44,655,954 | 8 | 4 | null | 2017-05-30 22:30:47.65 UTC | 23 | 2021-05-05 14:58:46.367 UTC | 2021-01-13 17:20:43.417 UTC | null | 2,413,303 | null | 4,785,114 | null | 1 | 72 | android|android-fragments|android-activity|master-detail|android-architecture-components | 116,423 | <p><strong>Updated on 6/12/2017,</strong></p>
<p><strong>Android Official provide a simple, precise example to example how the ViewModel works on Master-Detail template, you should take a look on it first.<a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing" rel="noreferrer">Share data between fragments</a></strong></p>
<p>As @CommonWare, @Quang Nguyen methioned, it is not the purpose for Yigit to make the call from master to detail but be better to use the Middle man pattern. But if you want to make some fragment transaction, it should be done in the activity. At that moment, the ViewModel class should be as static class in Activity and may contain some Ugly Callback to call back the activity to make the fragment transaction.</p>
<p>I have tried to implement this and make a simple project about this. You can take a look it. Most of the code is referenced from Google IO 2017, also the structure.
<a href="https://github.com/charlesng/SampleAppArch" rel="noreferrer">https://github.com/charlesng/SampleAppArch</a></p>
<p>I do not use Master Detail Fragment to implement the component, but the old one ( communication between fragment in ViewPager.) The logic should be the same.</p>
<p>But I found something is important using these components</p>
<ol>
<li>What you want to send and receive in the Middle man, they should be sent and received in View Model only</li>
<li>The modification seems not too much in the fragment class. Since it only change the implementation from "Interface callback" to "Listening and responding ViewModel"</li>
<li>View Model initialize seems important and likely to be called in the activity.</li>
<li>Using the MutableLiveData to make the source synchronized in activity only.</li>
</ol>
<p><strong>1.Pager Activity</strong></p>
<pre><code>public class PagerActivity extends AppCompatActivity {
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
private PagerAgentViewModel pagerAgentViewModel;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
pagerAgentViewModel = new ViewModelProvider(this).get(PagerAgentViewModel.class);
pagerAgentViewModel.init();
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
...Pager Implementation
}
}
</code></pre>
<p><strong>2.PagerAgentViewModel</strong> (It deserved a better name rather than this)</p>
<pre><code>public class PagerAgentViewModel extends ViewModel {
private final SavedStateHandle state;
private final MutableLiveData<String> messageContainerA;
private final MutableLiveData<String> messageContainerB;
public PagerAgentViewModel(SavedStateHandle state) {
this.state = state;
messageContainerA = state.getLiveData("Default Message");
messageContainerB = state.getLiveData("Default Message");
}
public void sendMessageToB(String msg)
{
messageContainerB.setValue(msg);
}
public void sendMessageToA(String msg)
{
messageContainerA.setValue(msg);
}
public LiveData<String> getMessageContainerA() {
return messageContainerA;
}
public LiveData<String> getMessageContainerB() {
return messageContainerB;
}
}
</code></pre>
<p><strong>3.BlankFragmentA</strong></p>
<pre><code>public class BlankFragmentA extends Fragment {
private PagerAgentViewModel viewModel;
public BlankFragmentA() {
// Required empty public constructor
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewModel = new ViewModelProvider(getActivity()).get(PagerAgentViewModel.class);
textView = (TextView) view.findViewById(R.id.fragment_textA);
// set the onclick listener
Button button = (Button) view.findViewById(R.id.btnA);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewModel.sendMessageToB("Hello B");
}
});
//setup the listener for the fragment A
viewModel.getMessageContainerA().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String msg) {
textView.setText(msg);
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_blank_a, container, false);
return view;
}
}
</code></pre>
<p><strong>4.BlankFragmentB</strong></p>
<pre><code>public class BlankFragmentB extends Fragment {
public BlankFragmentB() {
// Required empty public constructor
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewModel = new ViewModelProvider(getActivity()).get(PagerAgentViewModel.class);
textView = (TextView) view.findViewById(R.id.fragment_textB);
//set the on click listener
Button button = (Button) view.findViewById(R.id.btnB);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewModel.sendMessageToA("Hello A");
}
});
//setup the listener for the fragment B
viewModel.getMessageContainerB().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String msg) {
textView.setText(msg);
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_blank_b, container, false);
return view;
}
}
</code></pre> |
24,026,250 | The difference between \n and <br /> in php | <p>I was studying php with tutorial. I recognized that in php <br /> is sometimes use like this</p>
<pre><code>echo $myString."<br />"
</code></pre>
<p>Suddenly, there came another in the tutorial "\n" and I got confused. Can I use it just like I use</p>
<pre><code><br />
</code></pre>
<p>?</p>
<p>So like this?</p>
<pre><code>echo $mySting."\n"
</code></pre>
<p>Is it like a html tag?
What's the difference between</p>
<pre><code><br /> and \n?
</code></pre> | 24,026,282 | 3 | 4 | null | 2014-06-03 22:49:51.787 UTC | 2 | 2014-06-03 22:59:19.953 UTC | null | null | null | null | 3,696,062 | null | 1 | 4 | php | 47,556 | <p><code><br /></code> is a HTML line-break, whereas <code>\n</code> is a newline character in the source code.</p>
<p>In other words, <code><br /></code> will make a new line when you view the page as rendered HTML, whereas \n will make a new line when you view the source code.</p>
<p>Alternatively, if you're outputting to a console rather than somewhere that will be rendered by a web browser then <code>\n</code> will create a newline in the console output.</p> |
3,308,500 | Run interactive command line exe using c# | <p>I can run a command line process using <code>process.start()</code>.
I can provide input using standard input. After that when the process demands user input again, how can my program know and pass the input to that exe?</p> | 3,308,697 | 3 | 1 | null | 2010-07-22 11:52:52.15 UTC | 9 | 2014-05-05 23:43:55.283 UTC | 2014-05-05 23:43:55.283 UTC | null | 143,913 | null | 331,384 | null | 1 | 13 | c# | 15,612 | <p>There's an <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline.aspx" rel="noreferrer">example here</a> that sounds similar to what you need, using <code>Process.StandardInput</code> and a <code>StreamWriter</code>. </p>
<pre><code> Process sortProcess;
sortProcess = new Process();
sortProcess.StartInfo.FileName = "Sort.exe";
// Set UseShellExecute to false for redirection.
sortProcess.StartInfo.UseShellExecute = false;
// Redirect the standard output of the sort command.
// This stream is read asynchronously using an event handler.
sortProcess.StartInfo.RedirectStandardOutput = true;
sortOutput = new StringBuilder("");
// Set our event handler to asynchronously read the sort output.
sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
// Redirect standard input as well. This stream
// is used synchronously.
sortProcess.StartInfo.RedirectStandardInput = true;
sortProcess.Start();
// Use a stream writer to synchronously write the sort input.
StreamWriter sortStreamWriter = sortProcess.StandardInput;
// Start the asynchronous read of the sort output stream.
sortProcess.BeginOutputReadLine();
Console.WriteLine("Ready to sort up to 50 lines of text");
String inputText;
int numInputLines = 0;
do
{
Console.WriteLine("Enter a text line (or press the Enter key to stop):");
inputText = Console.ReadLine();
if (!String.IsNullOrEmpty(inputText))
{
numInputLines ++;
sortStreamWriter.WriteLine(inputText);
}
}
</code></pre>
<p>hope that helps</p> |
37,124,120 | Java 8 - omitting tedious collect method | <p>Java 8 stream api is very nice feature and I absolutely like it. One thing that get's on my nerves is that 90% of the time I want to have input as a collection and output as collections. The consequence is I have to call <code>stream()</code> and <code>collect()</code> method all the time:</p>
<pre><code>collection.stream().filter(p->p.isCorrect()).collect(Collectors.toList());
</code></pre>
<p>Is there any java api that would let me skip the stream and directly operate on collections (like <code>linq</code> in c#?):</p>
<pre><code>collection.filter(p->p.isCorrect)
</code></pre> | 37,126,123 | 10 | 9 | null | 2016-05-09 19:40:48.42 UTC | 8 | 2017-03-10 16:00:24.67 UTC | 2016-05-10 08:23:21.993 UTC | null | 699,233 | null | 3,364,192 | null | 1 | 59 | java|java-8|java-stream | 4,208 | <p>If you want to operate on collections <a href="http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/FluentIterable.html" rel="nofollow">Guava's FluentIterable</a> is a way to go!</p>
<p>Example (get id's of 10 first vip customers):</p>
<pre><code>FluentIterable
.from(customers)
.filter(customer -> customer.isVIP())
.transform(Client::getId)
.limit(10);
</code></pre> |
8,460,993 | P-end-tag (</p>) is not needed in HTML | <p><code></p></code> is only required in XHTML but not in HTML. Some times you have to close it anyway , e.g. when you align the paragraph left/right/center.</p>
<p>Would mixing the usage of <code></p></code> as in the following be a bad idea? Note that there is no ending <code></p></code> tag in the 1st and 3rd paragraph.</p>
<pre><code><h1>My article</h1>
<p>This is my 1st paragraph.
<p class="align=right">This is my 2nd paragraph</p>
<p>This is my 3rd paragraph.
</code></pre>
<p><strong>Reasons why I don't want to close the P-tags:</strong></p>
<ul>
<li>Easy to work with in my CMS (more demanding code to make it XHTML)</li>
<li>1kb lighter files</li>
</ul> | 8,461,004 | 4 | 10 | null | 2011-12-11 00:22:22.263 UTC | 6 | 2021-12-01 22:30:40.793 UTC | 2012-05-02 17:39:26.973 UTC | null | 264,541 | null | 673,108 | null | 1 | 31 | html|paragraph | 35,357 | <blockquote>
<p>P-end-tag is only required in XHTML, not in HTML.</p>
</blockquote>
<p>Correct</p>
<blockquote>
<p>But some times you have to close it any way eg. when you align the paragraph left/right/center.</p>
</blockquote>
<p>Incorrect. The only time you need an explicit end tag is when you want to end the paragraph and immediately follow it by something that is allowed inside a paragraph (such as text or an inline element). This is usually a bad idea.</p>
<blockquote>
<p>Would it for any reason be a bad idea to mix the usage of P-end-tag</p>
</blockquote>
<p>Only that consistency is a virtue which aids in code maintenance.</p> |
20,563,001 | Bootstrap Icons not showing in published ASP.NET MVC application | <p>--- NB: Go to the EDITED 2 section for summary ----</p>
<p>I have an ASP.NT MVC (4) application. I integrated (twitter)Bootstrap to it.
Bootstrap is working perfectly, but the icons does not show correctly when I publish the application.</p>
<p>I tried to republish the application without success.</p>
<p>For clarify I put some images here below.</p>
<p>When I run my application from VS2013 the result is this (which is OK):</p>
<p><img src="https://i.stack.imgur.com/GoDL9.png" alt="Local Icons"></p>
<p>In booth, IE and Chrome.</p>
<p>But when I run the published application the result is this (which is NOT ok):</p>
<ul>
<li>Chrome</li>
</ul>
<p><img src="https://i.stack.imgur.com/02cBg.png" alt="Published Chrome"></p>
<ul>
<li>IE (10)</li>
</ul>
<p><img src="https://i.stack.imgur.com/CkfKN.png" alt="Published IE"></p>
<p>This problem has, somehow, to be with the evaluated CSS but I don't know at which point this could be happening.</p>
<p>The evaluated css in the local application are this (which is OK):</p>
<ul>
<li>Chrome</li>
</ul>
<p><img src="https://i.stack.imgur.com/qpZ3M.png" alt="Local CSS Chrome"></p>
<ul>
<li>IE</li>
</ul>
<p><img src="https://i.stack.imgur.com/zgkbp.png" alt="Local CSS IE"></p>
<p>But In the published application I have this (which is NOT ok):</p>
<ul>
<li>Chrome:</li>
</ul>
<p><img src="https://i.stack.imgur.com/85V3j.png" alt="Published CSS Chrome"></p>
<ul>
<li>IE:</li>
</ul>
<p><img src="https://i.stack.imgur.com/x3DCk.png" alt="Publisehd CSS IE"></p>
<p>Some has experienced this behavior?</p>
<p>What can I do for solve this weird problem?</p>
<p>--------------------------- EDITED ------------------------------</p>
<p>I get the font files (<code>.eot</code>, <code>.svg</code>, <code>.ttf</code> and <code>.woff</code>) to be included when publishing my application.
When I access the default page (application root <code>http://localhost/</code>) which is the page showing the icons the files being showed in the Chrome's Developper Tools Network tab are:</p>
<p><img src="https://i.stack.imgur.com/SFgK5.png" alt="Network Tab"></p>
<p>Before including the files I was getting 404 errors for the files, so I could guess they continue to be requested even if they are not showed in the Network Tab.</p>
<p>Though, the icons are not showed correctly.</p>
<p>------------------------ EDITED 2 ---------------------------</p>
<p>Well, I restart my site in the IIS 7. And the request start to be triggered. These are the file requests showed in the Chrome's Developper Tools Network Tab:</p>
<p><img src="https://i.stack.imgur.com/E14XH.png" alt="New Requested files"></p>
<p>The resquest is then looking for the files in: <strong><code>/Content/themes/fonts/</code></strong> but they are in: <strong><code>/Content/themes/base/fonts/</code></strong></p>
<p>The <code>base</code> folder containt a <code>bootstrap</code> folder which containt the <code>bootstrap.css</code> file. In the CSS file there are this class referening the fonts files:</p>
<pre><code>@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
</code></pre>
<p>It seems the references to the fonts files are good as the the files tree is this:</p>
<p><img src="https://i.stack.imgur.com/GNA5D.png" alt="files tree"></p>
<p>I could change the class to be: </p>
<pre><code>@font-face {
font-family: 'Glyphicons Halflings';
src: url('../base/fonts/glyphicons-halflings-regular.eot');
src: url('../base/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../base/fonts/glyphicons-halflings-regular.woff') format('woff'), url('../base/fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../base/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
</code></pre>
<p>But, I would actually know what this is happening and how to solve it!
Besides, the icons will be showed in the published site but not in the local site (running from VS2013 with iisexpress).
<strong>Thank you in advance for your help!</strong></p> | 33,354,617 | 17 | 4 | null | 2013-12-13 09:26:49.167 UTC | 16 | 2019-01-02 08:38:48.19 UTC | 2014-03-11 13:18:05.023 UTC | null | 2,776,550 | null | 2,776,550 | null | 1 | 33 | css|asp.net-mvc|asp.net-mvc-4|twitter-bootstrap|less | 59,588 | <p>If your bundling your scripts and CSS then assets like images may not be found.</p>
<p>In your BundleConfig.cs file, create your bundle with CssRewriteUrlTransform:</p>
<pre><code>bundles.Add(new StyleBundle("~/Content/css/bootstrap").Include("~/Content/bootstrap.min.css", new CssRewriteUrlTransform()));
</code></pre>
<p>Include in _Layout.cshtml:</p>
<pre><code>@Styles.Render("~/Content/css/bootstrap")
</code></pre>
<p>Everything should be good. And yes, viewing what's happening over the network to see what URL is generating the 404s will help.</p>
<p>EDIT:
Ensure you are using Microsoft.AspNet.Web.Optimization v1.1.0. Confirmed version 1.1.3 causes this error as well.</p> |
26,141,001 | How to hide bin and obj folder from being displayed in solution explorer | <p>I am using Visual Studio 2008.</p>
<p>I have a windows forms application in VB. My project is working fine, but I would like to hide the bin and obj from being displayed in solution explorer. </p>
<p>The reason being that I could see other forms application in project in similar( bin and obj not displayed in solution explorer) way all though they have the bin and obj as folders. </p> | 33,721,163 | 1 | 4 | null | 2014-10-01 12:06:53.197 UTC | null | 2016-09-22 16:10:28.373 UTC | 2016-09-22 16:10:28.373 UTC | null | 1,070,452 | null | 2,564,024 | null | 1 | 28 | c#|.net|vb.net|visual-studio | 16,010 | <p>One of the buttons at the top of Solution Explorer is to <strong>Hide/Show All Files</strong>. When on/pressed/Show, the <code>bin</code> and <code>obj</code> folders show as dotted lines (may depend on themes and settings) to show they are VS folders:</p>
<p><a href="https://i.stack.imgur.com/g5PGw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/g5PGw.jpg" alt="enter image description here"></a></p>
<p>Note that when you have it as <code>Hide</code> some other things are hidden. <strong>My Project</strong> for instance can no longer be opened/expanded: </p>
<p><a href="https://i.stack.imgur.com/ZBQAV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ZBQAV.jpg" alt="enter image description here"></a></p>
<p>The <strong>My Project</strong> files are all VS/Designer files which can be changed elsewhere (Settings tab for instance), but sometimes it is nice to just open one to check something. </p>
<p>Unlike C# projects, VB also hides <strong>References</strong> so you cant right click it for the short Reference context menu. <code>Add Reference</code> is still on the longer <strong>Project</strong> context menu and of course in <strong>Project Properties</strong>.</p> |
25,968,071 | How to get the full URL of the current page using PHP | <p>What is the "less code needed" way to get parameters from an URL query string which is formatted like the following?</p>
<p><strong>My current url</strong> </p>
<pre><code>www.mysite.com/category/subcategory/#myqueryhash
</code></pre>
<p><strong>I put this code</strong> </p>
<pre><code>$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
</code></pre>
<p>It returns only <code>www.mysite.com/category/subcategory/</code></p>
<p><strong>Output should be :</strong> </p>
<pre><code>www.mysite.com/category/subcategory/#myqueryhash
</code></pre> | 25,968,193 | 1 | 5 | null | 2014-09-22 06:46:45.46 UTC | 6 | 2015-02-05 10:58:03.27 UTC | 2015-02-05 10:58:03.27 UTC | null | 2,311,948 | null | 2,311,948 | null | 1 | 18 | php|wordpress | 85,783 | <p>You can use this for HTTP request</p>
<pre><code><?php $current_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>
</code></pre>
<p>You can use this for HTTPS request</p>
<pre><code><?php $current_url="https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>
</code></pre>
<p>You can use this for HTTP/HTTPS request</p>
<pre><code><?php $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>
</code></pre> |
22,272,571 | Data input via shinyTable in R shiny application | <p>I want to build a shiny app that gets matrix data as input and returns a table based on some operations on it as output. By search I find that ShinyTable package could be useful. I tried below shiny codes but the result app appears gray out and without result.</p>
<pre><code>library(shinyTable)
shiny::runApp(list(
ui=pageWithSidebar(
headerPanel('Simple matrixInput')
,
sidebarPanel(
htable("tbl")
,
submitButton("OK")
)
,
mainPanel(
tableOutput(outputId = 'table.output')
))
,
server=function(input, output){
output$table.output <- renderTable({
input$tbl^2
}
, sanitize.text.function = function(x) x
)
}
))
</code></pre>
<p><strong>Any Idea?</strong></p> | 38,951,110 | 4 | 4 | null | 2014-03-08 17:27:18.417 UTC | 16 | 2017-01-13 18:52:23.183 UTC | null | null | null | null | 1,783,898 | null | 1 | 30 | r|shiny | 37,740 | <p>The <code>shinyTable</code> package has been greatly improved in the <a href="https://github.com/jrowen/rhandsontable" rel="noreferrer"><code>rhandsontable</code> package</a>. </p>
<p>Here is a minimal function that takes a data frame and runs a shiny app allowing to edit it and to save it in a <code>rds</code> file:</p>
<pre><code>library(rhandsontable)
library(shiny)
editTable <- function(DF, outdir=getwd(), outfilename="table"){
ui <- shinyUI(fluidPage(
titlePanel("Edit and save a table"),
sidebarLayout(
sidebarPanel(
helpText("Shiny app based on an example given in the rhandsontable package.",
"Right-click on the table to delete/insert rows.",
"Double-click on a cell to edit"),
wellPanel(
h3("Table options"),
radioButtons("useType", "Use Data Types", c("TRUE", "FALSE"))
),
br(),
wellPanel(
h3("Save"),
actionButton("save", "Save table")
)
),
mainPanel(
rHandsontableOutput("hot")
)
)
))
server <- shinyServer(function(input, output) {
values <- reactiveValues()
## Handsontable
observe({
if (!is.null(input$hot)) {
DF = hot_to_r(input$hot)
} else {
if (is.null(values[["DF"]]))
DF <- DF
else
DF <- values[["DF"]]
}
values[["DF"]] <- DF
})
output$hot <- renderRHandsontable({
DF <- values[["DF"]]
if (!is.null(DF))
rhandsontable(DF, useTypes = as.logical(input$useType), stretchH = "all")
})
## Save
observeEvent(input$save, {
finalDF <- isolate(values[["DF"]])
saveRDS(finalDF, file=file.path(outdir, sprintf("%s.rds", outfilename)))
})
})
## run app
runApp(list(ui=ui, server=server))
return(invisible())
}
</code></pre>
<p>For example, take the following data frame:</p>
<pre><code>> ( DF <- data.frame(Value = 1:10, Status = TRUE, Name = LETTERS[1:10],
Date = seq(from = Sys.Date(), by = "days", length.out = 10),
stringsAsFactors = FALSE) )
Value Status Name Date
1 1 TRUE A 2016-08-15
2 2 TRUE B 2016-08-16
3 3 TRUE C 2016-08-17
4 4 TRUE D 2016-08-18
5 5 TRUE E 2016-08-19
6 6 TRUE F 2016-08-20
7 7 TRUE G 2016-08-21
8 8 TRUE H 2016-08-22
9 9 TRUE I 2016-08-23
10 10 TRUE J 2016-08-24
</code></pre>
<p>Run the app and have fun (especially with the calendars ^^):</p>
<p><a href="https://i.stack.imgur.com/Zj7gW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Zj7gW.png" alt="enter image description here"></a></p>
<p>Edit the <em>handsontable</em>:</p>
<p><a href="https://i.stack.imgur.com/Cecyz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Cecyz.png" alt="enter image description here"></a></p>
<p>Click on the <em>Save</em> button. It saves the table in the file <code>table.rds</code>. Then read it in R:</p>
<pre><code>> readRDS("table.rds")
Value Status Name Date
1 1000 FALSE Mahmoud 2016-01-01
2 2000 FALSE B 2016-08-16
3 3 FALSE C 2016-08-17
4 4 TRUE D 2016-08-18
5 5 TRUE E 2016-08-19
6 6 TRUE F 2016-08-20
7 7 TRUE G 2016-08-21
8 8 TRUE H 2016-08-22
9 9 TRUE I 2016-08-23
10 10 TRUE J 2016-08-24
</code></pre> |
22,285,866 | Why RelayCommand | <p>I've been programming a lot in WPF lately but my View and ViewModel are not separate at this point. Well, it's partially. All my bindings concerned to text in text boxes, content for labels, lists in datagrids, ... are done by regular properties with a NotifyPropertyChanged event in them.</p>
<p>All my events for handling button clicks or text changed stuff is done by linking the events. Now, I wanted to start working with commands and found this article: <a href="http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute" rel="noreferrer">http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute</a>. It has an explanation of how to set up MVVM but I'm confused with the <code>RelayCommand</code>.</p>
<p>What job does it do?
Is it useable for all commands in my form?
How do I make the button disable when (a) certain text box(es) are not filled in?</p>
<hr>
<p>EDIT 1:</p>
<p>A good explanation to "Is it useable for all commands in my form?" is answered here: <a href="https://stackoverflow.com/a/22286816/3357699">https://stackoverflow.com/a/22286816/3357699</a></p>
<p>Here is the code I have so far: <a href="https://stackoverflow.com/a/22289358/3357699">https://stackoverflow.com/a/22289358/3357699</a></p> | 22,286,816 | 2 | 6 | null | 2014-03-09 18:00:15.767 UTC | 33 | 2021-12-20 14:26:25.427 UTC | 2017-05-23 12:10:41.023 UTC | null | -1 | null | 3,357,699 | null | 1 | 59 | c#|wpf|mvvm|binding|relaycommand | 91,171 | <p>Commands are used to <strong>separate the semantics and the object that invokes a command from the logic that executes the command</strong> i.e. it separates UI component from the logic that needs to be executed on command invocation. So, that you can test business logic separately using test cases and also your UI code is loosely coupled to business logic.</p>
<p>Now, that being said let's pick your questions one by one:</p>
<blockquote>
<p>What job does it do?</p>
</blockquote>
<p>I have added the details above. Hope it clears the usage of commands.</p>
<hr />
<blockquote>
<p>Is it usable for all commands in my form?</p>
</blockquote>
<p>Some controls exposed Command DependencyProperty like Button, MenuItem etc. which have some default event registered to it. For Button it's <code>Click</code> event. So, if you bind <code>ICommand</code> declared in ViewModel with Button's Command DP, it will be invoked whenever button is clicked on.</p>
<p>For other events, you can bind using <code>Interactivity triggers</code>. Refer to the sample <a href="http://coreclr.wordpress.com/2011/01/05/using-interaction-triggers-in-mvvm/" rel="nofollow noreferrer">here</a> how to use them to bind to <code>ICommand</code> in ViewModel.</p>
<hr />
<blockquote>
<p>How do I make the button disable when (a) certain text box(es) are not
filled in?</p>
</blockquote>
<p>The link you posted doesn't provide complete implementation of <code>RelayCommand</code>. It lacks the overloaded constructor to set <code>CanExecute</code> predicate which plays a key role in enabling/disabling the UI control to which your command is bound to.</p>
<p>Bound <code>TextBox</code>es with some properties in <code>ViewModel</code> and in <code>CanExecute</code> delegate returns <code>false</code> if any of the bound properties are <code>null</code> or empty which automatically disabled the control to which command is bound to.</p>
<hr />
<p>Full implementation of <code>RelayCommand</code>:</p>
<pre><code>public class RelayCommand<T> : ICommand
{
#region Fields
readonly Action<T> _execute = null;
readonly Predicate<T> _canExecute = null;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
/// </summary>
/// <param name="execute">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <remarks><seealso cref="CanExecute"/> will always return true.</remarks>
public RelayCommand(Action<T> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<T> execute, Predicate<T> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
///<summary>
///Defines the method that determines whether the command can execute in its current state.
///</summary>
///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
///<returns>
///true if this command can be executed; otherwise, false.
///</returns>
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute((T)parameter);
}
///<summary>
///Occurs when changes occur that affect whether or not the command should execute.
///</summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
///<summary>
///Defines the method to be called when the command is invoked.
///</summary>
///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to <see langword="null" />.</param>
public void Execute(object parameter)
{
_execute((T)parameter);
}
#endregion
}
</code></pre> |
10,992,644 | validateJarFile(servlet-api.jar) - jar not loaded in tomcat using eclipse | <blockquote>
<p>[Tomcat] validateJarFile(servlet-api.jar) - jar not loaded.
Offending class: javax/servlet/Servlet.class
org.apache.catalina.loader.WebappClassLoader validateJarFile INFO:
validateJarFile(\WEB-INF\lib\servlet-api.jar) - jar not
loaded. See Servlet Spec 2.3, section 9.7.2. Offending class:
javax/servlet/Servlet.class.</p>
</blockquote>
<p>I googled for this,I got to know that I am using servlet-api.jar in my project WEB-INF/lib, and also I am having same servlet-api.jar in tomcat/lib folder. so I have to remove servlet-api.jar, But if I remove that jar, I am getting error in import javax.servlet.*; so how to I solve this, help me for fix this error.Thanks in advance</p> | 10,992,689 | 2 | 0 | null | 2012-06-12 08:02:09.577 UTC | 1 | 2013-07-11 10:41:10.327 UTC | 2012-06-12 08:04:47.813 UTC | null | 260,990 | null | 1,443,848 | null | 1 | 14 | java|tomcat|servlets | 82,561 | <p>The error you are getting is because servlet-api needs to be on compile time build path, at runtime your app will have the servlet-api available from tomcat/lib</p>
<p>So add it to your build path simply, In short <code>servlet-api</code> is required at compile aswell as runtime </p> |
10,868,958 | What does sampler2D store? | <p>I've read a texture example in <code>OpenGL 2.1</code>. The fragment shader looks like this:</p>
<pre><code>#version 120
uniform sampler2D texture;
varying vec2 texcoord;
void main(void)
{
gl_FragColor = texture2D(texture, texcoord);
}
</code></pre>
<p>The <code>texcoord</code> is passed from vertex shader.</p>
<p>The following C++ rendering code is used:</p>
<pre><code>void render()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_id);
glUniform1i(unf_texture, 0);
}
</code></pre>
<p>I am confused about some things. I have some question:</p>
<ol>
<li><p>In the fragment shader, the texture is passed a zero value (by <code>glUniform1i()</code>). Is the value really zero? Is the value something else? </p></li>
<li><p>Is <code>glActiveTexture()</code> call really need?</p></li>
<li><p>Why do we pass a zero value in <code>glUniform1i()</code>?</p></li>
</ol> | 10,869,118 | 1 | 0 | null | 2012-06-03 08:35:15.78 UTC | 12 | 2019-07-27 01:19:53.517 UTC | 2019-07-27 01:18:28.207 UTC | null | 6,214,491 | null | 1,433,300 | null | 1 | 36 | opengl|glsl | 56,609 | <p>The <code>sampler2D</code> is bound to a <a href="http://www.opengl.org/wiki/Texture#Texture_image_units" rel="noreferrer">texture unit</a>. The <code>glUniform</code> call binds it to texture unit zero. The <code>glActiveTexture()</code> call is only needed if you are going to use multiple texture units (because <code>GL_TEXTURE0</code> is the default anyway).</p> |
11,172,221 | How do I include an environment variable inside an alias for bash? | <p>I am pretty new to bash, and I want to include an env for bash aliases.. I want to do something like the following</p>
<pre><code>alias foo="bar $(baz)"
</code></pre>
<p>So that I could do something like the following</p>
<pre><code>> baz=40
> foo
</code></pre>
<p>and foo will expand to the command <code>bar 40</code>. Currently the above does not work because $(baz) is expanded while making the alias. Do I have to wrap this inside a function or something?</p> | 11,172,247 | 3 | 0 | null | 2012-06-23 19:07:36.1 UTC | 5 | 2021-09-24 19:01:14.827 UTC | null | null | null | null | 601,095 | null | 1 | 38 | bash | 29,755 | <p>You need to use single quotes (<code>'</code>) to prevent bash from expanding the variable when creating the alias:</p>
<pre><code>$ alias foo='echo "$bar"'
$ bar="hello"
$ foo
hello
</code></pre> |
11,068,965 | How can I make TMUX be active whenever I start a new shell session? | <p>Instead of having to type <code>tmux</code> every time, <strong>how could I have <code>tmux</code> always be used for new session windows</strong>?</p>
<p>So if I have no terminal windows open and then I open one, how can that first session be in <code>tmux</code>?</p>
<p>Seems like a <code>.bashrc</code> sort of thing perhaps?</p> | 11,069,117 | 11 | 4 | null | 2012-06-17 04:41:15.46 UTC | 26 | 2018-10-03 10:56:30.477 UTC | 2014-01-08 17:39:45.697 UTC | null | 432,903 | null | 631,619 | null | 1 | 63 | shell|session|terminal|tmux | 47,828 | <p><em>warning</em> <strong>this can now 'corrupt' (make it unable to open a terminal window - which is not good!) your Ubuntu logins. Use with extreme caution and make sure you have a second admin account on the computer that you can log into in case you have the same problems I did. See my <em>other</em> answer for more details and a different approach.</strong></p>
<p>Given that warning, the simplest solution can be to append the <code>tmux</code> invocation to the end of your <code>.bashrc</code>, e.g.</p>
<pre><code>alias g="grep"
alias ls="ls --color=auto"
# ...other stuff...
if [[ ! $TERM =~ screen ]]; then
exec tmux
fi
</code></pre>
<p>Note that the <code>exec</code> means that the bash process which starts when you open the terminal is <em>replaced</em> by <code>tmux</code>, so <code>Ctrl-B D</code> (i.e. disconnect from tmux) actually closes the window, instead of returning to the original bash process, which is probably the behaviour you want?</p>
<p>Also, the <code>if</code> statement is required (it detects if the current bash window is in a tmux process already) otherwise each time you start tmux, the contained bash process will attempt to start its own tmux session, leading to an infinite number of nested tmuxen which can be, err, quite annoying (that said, it looks cool).</p>
<hr>
<p>However, there is a very small risk this can make <code>bash</code> behave in a way that other programs don't expect, since running bash can possibly cause it to turn into a tmux process, so it might be better to modify how you start your terminal emulator.</p>
<p>I use a small executable shell script <code>~/bin/terminal</code> (with <code>~/bin</code> in <code>$PATH</code>, so it is found automatically) that looks a bit like:</p>
<pre><code>#!/bin/sh
exec gnome-terminal -e tmux
</code></pre>
<p>(I don't use gnome-terminal, so you might have to remove the <code>exec</code>, I'm not sure.)</p>
<p>Now whenever you run the <code>terminal</code> scipt you have a terminal with tmux. You can add this to your menu/desktop/keyboard shortcuts to replace the default terminal.</p>
<p>(This approach also allows you to more easily customise other things about the terminal emulator later, if you ever desire.)</p> |
11,261,519 | chrome undo the action of "prevent this page from creating additional dialogs" | <p>I sometimes find that I need to re-enable alerting for debugging. Of course I can close the tab and reload it but Is there a better way? </p> | 11,261,591 | 8 | 0 | null | 2012-06-29 12:09:41.437 UTC | 14 | 2020-10-10 06:50:07.283 UTC | 2019-07-15 07:28:31.35 UTC | null | 1,000,551 | null | 459,384 | null | 1 | 122 | javascript|google-chrome|alert | 178,089 | <p>No. But you should really use <code>console.log()</code> instead of <code>alert()</code> for debugging.</p>
<p>In Chrome it even has the advantage of being able to print out entire objects (not just <code>toString()</code>).</p> |
12,755,003 | Creating a Procedure MySQL | <p>Im trying to convert a procedure from using sql plus to mysql but am getting a syntax error on the third line where it says (W_IN IN NUMBER) and it has IN highlighted as the syntax error. </p>
<p>SQL Plus:</p>
<pre><code>CREATE OR REPLACE PROCEDURE PRC_CUS_BALANCE_UPDATE (W_IN IN NUMBER) AS
W_CUS NUMBER := 0;
W_TOT NUMBER := 0;
BEGIN
-- GET THE CUS_CODE
SELECT CUS_CODE INTO W_CUS
FROM INVOICE
WHERE INVOICE.INV_NUMBER = W_IN;
-- UPDATES CUSTOMER IF W_CUS > 0
IF W_CUS > 0 THEN
UPDATE CUSTOMER
SET CUS_BALANCE = CUS_BALANCE +
(SELECT INV_TOTAL FROM INVOICE WHERE INV_NUMBER = W_IN)
WHERE CUS_CODE = W_CUS;
END IF;
END;
</code></pre>
<p>mySQL:</p>
<pre><code>-- Trigger DDL Statements
DELIMITER $$
CREATE PROCEDURE prc_cus_balance_update (W_IN IN NUMBER)
AS
W_CUS NUMBER = 0;
W_TOT NUMBER = 0;
BEGIN
-- GET CUS_CODE
SELECT CUS_CODE INTO W_CUS
FROM INVOICE
WHERE INVOICE.INV_NUMBER = W_IN;
-- UPDATES CUSTOMER IF W_CUS > 0
IF W_CUS > 0 THEN
UPDATE CUSTOMER
SET CUS_BALANCE = CUS_BALANCE +
(SELECT INV_TOTAL FROM INVOICE WHERE INV_NUMBER = W_IN)
WHERE CUS_CODE = W_CUS;
END IF;
END $$
DELIMITER ;
</code></pre>
<p>Any help is greatly appreciated!</p> | 12,755,426 | 2 | 0 | null | 2012-10-05 22:47:02.173 UTC | null | 2012-10-05 23:53:20.527 UTC | 2012-10-05 23:22:38.447 UTC | null | 1,724,262 | null | 1,724,262 | null | 1 | 13 | mysql | 59,644 | <p>This compiles in MySQL 5.5.23:</p>
<pre><code>-- Trigger DDL Statements
DELIMITER $$
DROP PROCEDURE IF EXISTS prc_cus_balance_update;
CREATE PROCEDURE prc_cus_balance_update (IN W_IN INT UNSIGNED)
BEGIN
DECLARE W_CUS INT UNSIGNED DEFAULT 0;
DECLARE W_TOT DOUBLE DEFAULT 0; -- NOT USED?
-- GET CUS_CODE
SELECT CUS_CODE INTO W_CUS
FROM INVOICE
WHERE INVOICE.INV_NUMBER = W_IN;
-- UPDATES CUSTOMER IF W_CUS > 0
IF W_CUS > 0 THEN
UPDATE CUSTOMER
SET CUS_BALANCE = CUS_BALANCE +
(SELECT INV_TOTAL FROM INVOICE WHERE INV_NUMBER = W_IN)
WHERE CUS_CODE = W_CUS;
END IF;
END $$
DELIMITER ;
</code></pre>
<p>Of course, in this case, a stored procedure is not needed, as the following query will perform the same function much faster (and easier to understand):</p>
<pre><code>UPDATE
CUSTOMER c
INNER JOIN
INVOICE i ON i.CUS_CODE = c.CUS_CODE
SET
c.CUS_BALANCE = c.CUS_BALANCE + i.INV_TOTAL
WHERE
i.INV_NUMBER = W_IN
</code></pre> |
13,167,058 | Deriving from a class that has Annotation @PostConstruct | <p>If you have a parent class which uses the <code>@PostConstruct</code> annotation and you create a child class that derives from it. Will the <code>@PostConstruct</code> method be called automatically each time an instance of the child class is created? since that <code>@PostConstruct</code> method is called each time an instance of the the parent is created. </p>
<p>I Know that in the child class it calls <code>super();</code> for us automatically without us having to call it. </p>
<p>im just not sure if the <code>@PostConstruct</code> annotation is automatically called if that child class calls the <code>super();</code> constructor. </p> | 13,168,017 | 1 | 3 | null | 2012-10-31 20:35:43.417 UTC | 2 | 2015-06-02 06:24:17.427 UTC | 2013-07-29 13:00:11.667 UTC | null | 49,548 | null | 1,203,394 | null | 1 | 35 | java|jakarta-ee|inheritance|annotations | 10,978 | <p>After testing this scenario, the <code>@PostConstruct</code> method in the base class WILL automatically be called. </p>
<p>The flow goes like this:</p>
<ol>
<li>When the child class is created, you are in the constructor of the child class, you then are forced into the parent class automatically. </li>
<li>Once the parent class constructor is done you are sent back to the child class' constructor.</li>
<li>Once the child class constructor is done you are automatically sent to the PARENT classes <code>@PostConstruct</code> method</li>
</ol> |
12,963,165 | What characters need to be escaped in .NET Regex? | <p>In a .NET <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx"><code>Regex</code></a> pattern, what special characters need to be escaped in order to be used literally?</p> | 12,963,199 | 4 | 0 | null | 2012-10-18 20:26:54.74 UTC | 6 | 2017-06-19 12:45:07.187 UTC | null | null | null | null | 546,561 | null | 1 | 40 | .net|regex|escaping | 22,586 | <p>I don't know the complete set of characters - but I wouldn't rely on the knowledge anyway, and I wouldn't put it into code. Instead, I would use <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx" rel="noreferrer"><code>Regex.Escape</code></a> whenever I wanted some literal text that I wasn't sure about:</p>
<pre><code>// Don't actually do this to check containment... it's just a little example.
public bool RegexContains(string haystack, string needle)
{
Regex regex = new Regex("^.*" + Regex.Escape(needle) + ".*$");
return regex.IsMatch(haystack);
}
</code></pre> |
12,795,767 | Trying to add 3 days in Milliseconds to current Date | <pre><code>var dateObj = new Date();
var val = dateObj.getTime();
//86400 * 1000 * 3 Each day is 86400 seconds
var days = 259200000;
val = val + days;
dateObj.setMilliseconds(val);
val = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear();
alert(val);
</code></pre>
<p>I am trying to take the current date, add three days of milliseconds to it, and have the date stamp show 3 days later from the current. For example - if today is 10/09/2012 then I would like it to say 10/12/2012. </p>
<p>this method is not working, I am getting the months and days way off. Any suggestions?</p> | 12,795,802 | 5 | 2 | null | 2012-10-09 08:22:02.8 UTC | 4 | 2022-01-12 16:07:50.947 UTC | 2018-03-06 09:12:18.63 UTC | null | 271,200 | null | 1,483,954 | null | 1 | 51 | javascript|date | 97,208 | <p>To add time, get the current date then add, as milliseconds, the specific amount of time, then create a new date with the value:</p>
<pre><code>// get the current date & time (as milliseconds since Epoch)
const currentTimeAsMs = Date.now();
// Add 3 days to the current date & time
// I'd suggest using the calculated static value instead of doing inline math
// I did it this way to simply show where the number came from
const adjustedTimeAsMs = currentTimeAsMs + (1000 * 60 * 60 * 24 * 3);
// create a new Date object, using the adjusted time
const adjustedDateObj = new Date(adjustedTimeAsMs);
</code></pre>
<p>To explain this further; the reason <code>dataObj.setMilliseconds()</code> doesn't work is because it sets the dateobj's milliseconds PROPERTY to the specified value(a value between 0 and 999). It does not set, as milliseconds, the date of the object.</p>
<pre><code>// assume this returns a date where milliseconds is 0
dateObj = new Date();
dateObj.setMilliseconds(5);
console.log(dateObj.getMilliseconds()); // 5
// due to the set value being over 999, the engine assumes 0
dateObj.setMilliseconds(5000);
console.log(dateObj.getMilliseconds()); // 0
</code></pre>
<p>References:<br />
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now" rel="noreferrer"><code>Date.now()</code></a><br />
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date" rel="noreferrer"><code>new Date()</code></a><br />
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds" rel="noreferrer"><code>Date.setMilliseconds()</code></a></p> |
12,864,302 | How to set headers in http get request? | <p>I'm doing a simple http GET in Go:</p>
<pre><code>client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
res, _ := client.Do(req)
</code></pre>
<p>But I can't found a way to customize the request header in the <a href="http://golang.org/pkg/net/http/" rel="noreferrer">doc</a>, thanks</p> | 12,864,342 | 4 | 0 | null | 2012-10-12 17:33:03.57 UTC | 26 | 2022-05-20 06:42:51.537 UTC | 2016-03-18 16:32:23.67 UTC | null | 503,099 | null | 325,241 | null | 1 | 230 | http|go | 233,700 | <p>The <code>Header</code> field of the Request is public. You may do this :</p>
<pre><code>req.Header.Set("name", "value")
</code></pre> |
50,692,160 | React - componentWillReceiveProps alternative | <p>I use React with NextJS.</p>
<p>I have a component which is basically a table which gives some summary.
Based on some UI selection, this component is expected to show appropriate summary.</p>
<p>The below code works perfectly fine.</p>
<pre><code>class Summary extends Component{
state = {
total: 0,
pass: 0,
fail: 0,
passp: 0,
failp: 0
}
componentWillReceiveProps(props){
let total = props.results.length;
let pass = props.results.filter(r => r.status == 'pass').length;
let fail = total - pass;
let passp = (pass/(total || 1) *100).toFixed(2);
let failp = (fail/(total || 1) *100).toFixed(2);
this.setState({total, pass, fail, passp, failp});
}
render() {
return(
<Table color="teal" >
<Table.Header>
<Table.Row textAlign="center">
<Table.HeaderCell>TOTAL</Table.HeaderCell>
<Table.HeaderCell>PASS</Table.HeaderCell>
<Table.HeaderCell>FAIL</Table.HeaderCell>
<Table.HeaderCell>PASS %</Table.HeaderCell>
<Table.HeaderCell>FAIL %</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row textAlign="center">
<Table.Cell>{this.state.total}</Table.Cell>
<Table.Cell >{this.state.pass}</Table.Cell>
<Table.Cell >{this.state.fail}</Table.Cell>
<Table.Cell >{this.state.passp}</Table.Cell>
<Table.Cell >{this.state.failp}</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
);
}
}
</code></pre>
<p>Looks like <code>componentWillReceiveProps</code> will be deprecated. I tried other options like <code>shouldComponentUpdate</code> etc..they all lead to infinite loop. What is best approach to update the state from the props to re-render this component?</p> | 50,692,227 | 1 | 6 | null | 2018-06-05 04:40:57.393 UTC | 6 | 2020-05-15 00:01:22.377 UTC | null | null | null | null | 4,081,949 | null | 1 | 36 | reactjs|next.js | 44,035 | <p>From react <a href="https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html" rel="noreferrer">blog</a>, 16.3 introduced deprecation notices for <code>componentWillRecieveProps</code>.</p>
<p>As a workaround, you would use the method </p>
<pre><code>static getDerivedStateFromProps(nextProps, prevState)
</code></pre>
<p>therefore </p>
<pre><code>componentWillReceiveProps(props){
let total = props.results.length;
let pass = props.results.filter(r => r.status == 'pass').length;
let fail = total - pass;
let passp = (pass/(total || 1) *100).toFixed(2);
let failp = (fail/(total || 1) *100).toFixed(2);
this.setState({total, pass, fail, passp, failp});
}
</code></pre>
<p>becomes</p>
<pre><code>static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.total !== prevState.total) {
return ({ total: nextProps.total }) // <- this is setState equivalent
}
return null
}
</code></pre> |
4,609,933 | How to list installed packages from a given repo using yum | <p>I want to list all packages I have installed on a system from a given repo using yum. Usually to do this I use <code>yum list installed | grep "something"</code>. But now I am faced with a problem. The repo I am interested in does not have that "something" for me to grep. The packages from that repo do not have any distinctive characteristics. How do I list them? </p>
<p>I looked through yum man pages but did not find anything. I wonder if there are other commands I could use.</p> | 4,934,975 | 2 | 2 | null | 2011-01-05 22:40:25.077 UTC | 18 | 2013-03-11 17:44:25.913 UTC | 2012-08-27 14:03:32.58 UTC | null | 11,343 | null | 18,297 | null | 1 | 66 | centos|fedora|yum | 141,766 | <p>On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:</p>
<pre><code>yumdb search from_repo repoid
</code></pre>
<p>(or repoquery and grep -- don't grep yum output).
However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:</p>
<p><a href="http://james.fedorapeople.org/yum/commands/find-repos-of-install.py" rel="noreferrer">http://james.fedorapeople.org/yum/commands/find-repos-of-install.py</a></p>
<p>As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?</p> |
26,613,570 | HDF5 file created with h5py can't be opened by h5py | <p>I created an HDF5 file apparently without any problems, under Ubuntu 12.04 (32bit version), using Anaconda as Python distribution and writing in ipython notebooks. The underlying data are all numpy arrays. For example,</p>
<pre><code>import numpy as np
import h5py
f = h5py.File('myfile.hdf5','w')
group = f.create_group('a_group')
group.create_dataset(name='matrix', data=np.zeros((10, 10)), chunks=True, compression='gzip')
</code></pre>
<p>If I try to open this file from a new iypthon notebook, though, I get an error message:</p>
<pre><code>f = h5py.File('myfile.hdf5', "r")
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-4-b64ac5089cd4> in <module>()
----> 1 f = h5py.File(file_name, "r")
/home/sarah/anaconda/lib/python2.7/site-packages/h5py/_hl/files.pyc in __init__(self, name, mode, driver, libver, userblock_size, **kwds)
220
221 fapl = make_fapl(driver, libver, **kwds)
--> 222 fid = make_fid(name, mode, userblock_size, fapl)
223
224 Group.__init__(self, fid)
/home/sarah/anaconda/lib/python2.7/site-packages/h5py/_hl/files.pyc in make_fid(name, mode, userblock_size, fapl, fcpl)
77
78 if mode == 'r':
---> 79 fid = h5f.open(name, h5f.ACC_RDONLY, fapl=fapl)
80 elif mode == 'r+':
81 fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)
/home/sarah/anaconda/lib/python2.7/site-packages/h5py/h5f.so in h5py.h5f.open (h5py/h5f.c:1741)()
IOError: Unable to open file (Unable to find a valid file signature)
</code></pre>
<p>Can you tell me what that missing file signature is? Did I miss something when I created the file?</p> | 26,730,843 | 2 | 8 | null | 2014-10-28 16:31:03.83 UTC | 6 | 2022-09-04 05:56:30.643 UTC | 2014-10-29 15:30:12.743 UTC | null | 1,498,018 | null | 1,498,018 | null | 1 | 23 | python|numpy|io|hdf5|h5py | 55,342 | <p>Since we resolved the issue in the comments on my question, I'm writing the results out here to mark it as solved.</p>
<p>The main problem was that I forgot to close the file after I created it. There would have been two simple options, either:</p>
<pre><code>import numpy as np
import h5py
f = h5py.File('myfile.hdf5','w')
group = f.create_group('a_group')
group.create_dataset(name='matrix', data=np.zeros((10, 10)), chunks=True, compression='gzip')
f.close()
</code></pre>
<p>or, my favourite because the file is closed automatically:</p>
<pre><code>import numpy as np
import h5py
with h5py.File('myfile.hdf5','w') as f:
group = f.create_group('a_group')
group.create_dataset(name='matrix', data=np.zeros((10, 10)), chunks=True, compression='gzip')
</code></pre> |
10,127,491 | How to publish my MVC 3 web application onto IIS7 | <p>if possible I need total from the beginning utter beginner advice on how to get my ASP.Net MVC 3 Razor Visual Studio 10 web application live onto my IIS 7 webserver please?</p>
<p>I've never tried to publish this before, and wondering what I'm missing? </p>
<p>I've clicked "Publish" on Visual Studio Express 10, created a "published" version of the website. I've uploaded it to my webserver, however can't make it load on the net?</p>
<p>Appreciate some guidance please? (not sure how / what default documents work etc...?)</p> | 10,127,511 | 1 | 3 | null | 2012-04-12 16:10:06.157 UTC | 4 | 2012-12-04 20:26:51.93 UTC | null | null | null | null | 1,279,167 | null | 1 | 6 | visual-studio-2010|asp.net-mvc-3|web-applications|publish | 39,963 | <p>By far the easiest approach is to use Web Application Deployment.</p>
<p>This blog by Scott Gu gives a great intro</p>
<p><a href="http://weblogs.asp.net/scottgu/archive/2010/07/29/vs-2010-web-deployment.aspx" rel="noreferrer">http://weblogs.asp.net/scottgu/archive/2010/07/29/vs-2010-web-deployment.aspx</a></p>
<p>The article talks about web.config transformations (ability to have a .Release and a .Debug version of your web.config). Later, that capability was generalized through an add-on package to work for any XML-structured file in your deployment (for example, I use it with NLog configuration files).</p>
<p><a href="http://www.hanselman.com/blog/SlowCheetahWebconfigTransformationSyntaxNowGeneralizedForAnyXMLConfigurationFile.aspx" rel="noreferrer">http://www.hanselman.com/blog/SlowCheetahWebconfigTransformationSyntaxNowGeneralizedForAnyXMLConfigurationFile.aspx</a></p> |
10,198,965 | Android get Facebook friends who have app downloaded | <p>I am using the Facebook Android SDK. Is there an easy way to get a user's friends who have downloaded the app? For example, the app Draw Something implements this. I can't seem to find any information on this subject</p>
<p>I would guess that if it was possible, some extra information would be needed in the httppost to access this information. </p> | 15,196,047 | 3 | 1 | null | 2012-04-17 20:51:16.943 UTC | 12 | 2014-08-05 00:58:44.717 UTC | null | null | null | null | 1,045,229 | null | 1 | 7 | android|facebook | 15,251 | <p><em>*</em> Note: since 3.14 version, me/friends will only return friends that also use the app, so below implementation is deprecated. See the new "Invitable Friends" or "Taggable Friends" APIs for alternatives.</p>
<p>Using the new <strong>Facebook SDK for Android (3.0)</strong> is very easy to get your user's friend list.
Following is the code:</p>
<pre><code>private void requestFacebookFriends(Session session) {
Request.executeMyFriendsRequestAsync(session,
new Request.GraphUserListCallback() {
@Override
public void onCompleted(List<GraphUser> users,
Response response) {
// TODO: your code for friends here!
}
});
}
</code></pre>
<p>Nevertheless, in order to get the user's friends who are using your Facebook app is a little bit complicated (due to Facebook API documentation). But <strong>yes, it is possible</strong>.</p>
<p>First of all, create your request:</p>
<pre><code>private Request createRequest(Session session) {
Request request = Request.newGraphPathRequest(session, "me/friends", null);
Set<String> fields = new HashSet<String>();
String[] requiredFields = new String[] { "id", "name", "picture",
"installed" };
fields.addAll(Arrays.asList(requiredFields));
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}
</code></pre>
<p>Note that you need to insert the field <strong>"installed"</strong> in your request. I'm requesting the user picture path with the same request. Check your possibilities <a href="https://developers.facebook.com/docs/reference/api/user/">here</a>.</p>
<p>Next, you can use above code to create your request and then get your friends:</p>
<pre><code>private void requestMyAppFacebookFriends(Session session) {
Request friendsRequest = createRequest(session);
friendsRequest.setCallback(new Request.Callback() {
@Override
public void onCompleted(Response response) {
List<GraphUser> friends = getResults(response);
// TODO: your code here
}
});
friendsRequest.executeAsync();
}
</code></pre>
<p>Note that using this generic request, you don't receive a GraphUser list as response. You'll need following code to get the response as GraphUser list:</p>
<pre><code>private List<GraphUser> getResults(Response response) {
GraphMultiResult multiResult = response
.getGraphObjectAs(GraphMultiResult.class);
GraphObjectList<GraphObject> data = multiResult.getData();
return data.castToListOf(GraphUser.class);
}
</code></pre>
<p>Now you can use your user's friend list, with the information if each of your friends use your Facebook app:</p>
<pre><code>GraphUser user = friends.get(0);
boolean installed = false;
if(user.getProperty("installed") != null)
installed = (Boolean) user.getProperty("installed");
</code></pre> |
9,770,354 | Empty input box onclick in jQuery | <p>I've no idea why this isn't working, but I'm sure it's a very common bit of Javascript. My syntax is clearly lacking, and I don't know why:</p>
<pre><code><input type="text" value="search" id="search" name="q" onclick="javascript:if($(this).val() == 'search') {$(this).val() = '';} return false;" />
</code></pre> | 9,770,441 | 8 | 0 | null | 2012-03-19 12:39:19.58 UTC | 2 | 2019-12-25 12:37:42.607 UTC | 2019-12-25 12:37:42.607 UTC | null | 4,370,109 | null | 199,700 | null | 1 | 9 | javascript|jquery|onclick|jquery-events | 56,906 | <p>Your issue is with this line of code:</p>
<pre><code>$(this).val() = ''
</code></pre>
<p>The proper way to set a value in jQuery is:</p>
<pre><code>$(this).val("Your value here");
</code></pre>
<p>In addition, inline JS is never a good idea. Use this instead:</p>
<pre><code>$("#search").on("click", function() {
if ($(this).val() == "search")
$(this).val("")
});
</code></pre>
<p>Here's <a href="http://jsfiddle.net/JamesHill/Yu97Z/" rel="noreferrer">a working fiddle</a>.</p>
<p>References: <a href="http://api.jquery.com/val/" rel="noreferrer">jQuery <code>.val()</code></a></p> |
10,040,297 | How exactly can I replace an iframe with a div and Javascript? | <p>I have a page that loads an external HTML page into an iFrame. There are two problems I am facing with this:</p>
<ol>
<li>The iFrame is always a fixed height, but I want it to expand
vertically depending on the height of the content.</li>
<li>The content inside the iFrame can not inherit the CSS styles
attached to the HTML page that contains it. The HTML inside the
iFrame has to have it's own link or separate style sheet.</li>
</ol>
<p>I could be wrong about either of those points, so if I am, please let me know and then I will continue to use the iFrame.</p>
<p>Otherwise, <em>is there a simple <strong>Javascript</strong> call that can load an external HTML file into a <strong>DIV</em></strong>?</p>
<p>Just to be clear, since it seems some people have misunderstood me:</p>
<p>I am asking <strong>how to replace an iframe with a DIV and Javascript</strong> in order to get the functionality I mention above. I am <strong>not</strong> looking for ways to make iFrames behave differently.</p>
<p><em>(I thought this would be fairly common, but most of the questions and information I've found in this site and on the web seems to be situation specific and asks for additional functionality that I don't need and complicates the issue. However, if I've missed something and this is a duplicate, I wouldn't be offended if this got closed.)</em></p> | 10,047,186 | 5 | 4 | null | 2012-04-06 07:09:17.117 UTC | 7 | 2016-08-10 02:42:34.143 UTC | 2012-04-07 06:41:48.597 UTC | null | 184,108 | null | 184,108 | null | 1 | 13 | javascript|iframe|html | 39,990 | <p>You can make an ajax call to fetch your html page and add it to the div. For example using JQuery:</p>
<p><code>$.get('yourPage.html', function(data) {
$('#yourDiv').html(data);
});</code></p>
<p>Read more at: <a href="http://api.jquery.com/jQuery.get/">http://api.jquery.com/jQuery.get/</a></p> |
9,858,495 | Using flush() before close() | <p>As per the java docs, invoking close() on any java.io Streams automatically invokes flush(). But I have seen in lot of examples, even in production codes, developers have explicitly used flush() just before close(). In what conditions we need to use flush() just before close()?</p> | 9,858,630 | 4 | 3 | null | 2012-03-25 07:10:10.363 UTC | 12 | 2021-02-04 09:42:59.67 UTC | null | null | null | null | 206,491 | null | 1 | 50 | java|iostream | 39,226 | <p>Developer get into a habit of calling flush() after writing something which must be sent.</p>
<p>IMHO Using flush() then close() is common when there has just been a write e.g.</p>
<pre><code>// write a message
out.write(buffer, 0, size);
out.flush();
// finished
out.close();
</code></pre>
<p>As you can see the flush() is redundant, but means you are following a pattern.</p> |
9,966,826 | Save and render a webpage with PhantomJS and node.js | <p>I'm looking for an example of requesting a webpage, waiting for the JavaScript to render (JavaScript modifies the DOM), and then grabbing the HTML of the page.</p>
<p>This should be a simple example with an obvious use-case for PhantomJS. I can't find a decent example, the documentation seems to be all about command line use.</p> | 9,978,162 | 6 | 6 | null | 2012-04-01 18:01:23.727 UTC | 40 | 2019-04-01 23:20:35.547 UTC | 2012-12-26 04:10:49.093 UTC | null | 527,702 | null | 663,447 | null | 1 | 62 | javascript|html|node.js|web-scraping|phantomjs | 62,961 | <p>From your comments, I'd guess you have 2 options</p>
<ol>
<li>Try to find a phantomjs node module - <a href="https://github.com/amir20/phantomjs-node" rel="nofollow noreferrer">https://github.com/amir20/phantomjs-node</a> </li>
<li>Run phantomjs as a child process inside node - <a href="http://nodejs.org/api/child_process.html" rel="nofollow noreferrer">http://nodejs.org/api/child_process.html</a></li>
</ol>
<p>Edit: </p>
<p>It seems the child process is suggested by phantomjs as a way of interacting with node, see faq - <a href="http://code.google.com/p/phantomjs/wiki/FAQ" rel="nofollow noreferrer">http://code.google.com/p/phantomjs/wiki/FAQ</a></p>
<p>Edit:</p>
<p>Example Phantomjs script for getting the pages HTML markup:</p>
<pre><code>var page = require('webpage').create();
page.open('http://www.google.com', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var p = page.evaluate(function () {
return document.getElementsByTagName('html')[0].innerHTML
});
console.log(p);
}
phantom.exit();
});
</code></pre> |
9,946,322 | How to generate an import library (LIB-file) from a DLL? | <p>Is it possible to autogenerate a MSVC import library (LIB-file) from a DLL? How?</p> | 9,946,390 | 5 | 6 | null | 2012-03-30 15:48:05.593 UTC | 24 | 2022-04-16 10:18:40.46 UTC | 2014-06-03 14:52:47.94 UTC | null | 1,329,652 | null | 133,374 | null | 1 | 75 | windows|visual-c++|dll | 36,407 | <p>You can <a href="https://web.archive.org/web/20130330132630/http://www.coderetard.com/2009/01/21/generate-a-lib-from-a-dll-with-visual-studio" rel="noreferrer">generate a DEF file using dumpbin /exports</a>:</p>
<pre><code>echo LIBRARY SQLITE3 > sqlite3.def
echo EXPORTS >> sqlite3.def
for /f "skip=19 tokens=4" %A in ('dumpbin /exports sqlite3.dll') do echo %A >> sqlite3.def
</code></pre>
<p>The librarian can use this DEF file to generate the LIB:</p>
<pre><code>lib /def:sqlite3.def /out:sqlite3.lib /machine:x86
</code></pre>
<p>All of the filenames (<code>sqlite3.dll</code>, <code>sqlite3.def</code>, etc.) should be prepended with full paths.</p> |
9,819,602 | Union of dict objects in Python | <p>How do you calculate the union of two <code>dict</code> objects in Python, where a <code>(key, value)</code> pair is present in the result iff <code>key</code> is <code>in</code> either dict (unless there are duplicates)?</p>
<p>For example, the union of <code>{'a' : 0, 'b' : 1}</code> and <code>{'c' : 2}</code> is <code>{'a' : 0, 'b' : 1, 'c' : 2}</code>.</p>
<p>Preferably you can do this without modifying either input <code>dict</code>. Example of where this is useful: <a href="https://stackoverflow.com/questions/1041639/get-a-dict-of-all-variables-currently-in-scope-and-their-values">Get a dict of all variables currently in scope and their values</a></p> | 9,819,617 | 4 | 6 | null | 2012-03-22 09:36:47.34 UTC | 15 | 2021-09-21 13:56:20.04 UTC | 2017-05-23 10:31:36.66 UTC | null | -1 | null | 319,931 | null | 1 | 205 | python|dictionary|associative-array|idioms|set-operations | 115,271 | <p><a href="https://stackoverflow.com/questions/2255878/merging-dictionaries-in-python">This question</a> provides an idiom. You use one of the dicts as keyword arguments to the <code>dict()</code> constructor:</p>
<pre><code>dict(y, **x)
</code></pre>
<p>Duplicates are resolved in favor of the value in <code>x</code>; for example</p>
<pre><code>dict({'a' : 'y[a]'}, **{'a', 'x[a]'}) == {'a' : 'x[a]'}
</code></pre> |
11,515,237 | Magento cache not getting cleared | <p>I had some configuration issues in my <strong>local.xml</strong>, which I cannot load my magento frontend nor my admin panel, then I fixed the issue I had in my <strong>local.xml</strong>, and to get my new config to be loaded, I deleted everything in <strong>/var/cache</strong> and even whats there in <strong>/var/session</strong> folders. But to my surprise Magento still loads the old local.xml settings. </p>
<p>I tried with restarting apache and cleared my browser cache, nothing works. </p>
<p>Any ideas?? </p> | 11,516,317 | 2 | 0 | null | 2012-07-17 02:25:23.97 UTC | 11 | 2019-06-17 00:31:14.567 UTC | 2015-05-01 01:33:10.297 UTC | null | 1,228,293 | null | 1,228,293 | null | 1 | 7 | xml|magento|caching|local | 14,123 | <p>Manage to Solve the issue and its the weirdest thing ever. When I change the local.xml to fix the issue I put a backup of the old file saying local_back.xml. I just delete that file and now everything is working fine.
No idea why Magento pick that file up. Any ways issue has been solved. </p>
<p>Note : See comments below for more details, it is the .xml file extension</p> |
11,819,185 | Steps to creating an NFA from a regular expression | <p>I'm having issues 'describing each step' when creating an NFA from a regular expression. The question is as follows:</p>
<p>Convert the following regular expression to a non-deterministic finite-state automaton (NFA), clearly describing the steps of the algorithm that you use:
(b|a)*b(a|b)</p>
<p>I've made a simple 3-state machine but it's very much from intuition.
This is a question from a past exam written by my lecturer, who also wrote the following explanation of Thompson's algorithm: <a href="http://www.cs.may.ie/staff/jpower/Courses/Previous/parsing/node5.html" rel="noreferrer">http://www.cs.may.ie/staff/jpower/Courses/Previous/parsing/node5.html</a></p>
<p>Can anyone clear up how to 'describe each step clearly'? It just seems like a set of basic rules rather than an algorithm with steps to follow.</p>
<p>Maybe there's an algorithm I've glossed over somewhere but so far I've just created them with an educated guess.</p> | 11,820,585 | 3 | 0 | null | 2012-08-05 18:58:15.553 UTC | 25 | 2019-07-09 04:57:25.047 UTC | 2014-05-16 00:23:25.9 UTC | null | 650,492 | null | 1,260,978 | null | 1 | 27 | theory|compiler-theory|nfa | 50,529 | <p><strong>Short version for general approach.</strong><br>
There's an algo out there called the Thompson-McNaughton-Yamada Construction Algorithm or sometimes just "Thompson Construction." One builds intermediate NFAs, filling in the pieces along the way, while respecting operator precedence: first parentheses, then Kleene Star (e.g., a*), then concatenation (e.g., ab), followed by alternation (e.g., a|b).</p>
<p><strong>Here's an in-depth walkthrough for building (b|a)*b(a|b)'s NFA</strong></p>
<p><em>Building the top level</em></p>
<ol>
<li><p>Handle parentheses. Note: In actual implementation, it can make sense to handling parentheses via a recursive call on their contents. For the sake of clarity, I'll defer evaluation of anything inside of parens.</p></li>
<li><p>Kleene Stars: only one * there, so we build a placeholder Kleene Star machine called P (which will later contain b|a).
Intermediate result:<br>
<img src="https://i.stack.imgur.com/DIdvB.png" alt="Non-Deterministic Finite Automata for P*"></p></li>
<li><p>Concatenation: Attach P to b, and attach b to a placeholder machine called Q (which will contain (a|b). Intermediate result:<br>
<img src="https://i.stack.imgur.com/81Kgo.png" alt="Non-Deterministic Finite Automata for P*bQ"></p></li>
<li><p>There's no alternation outside of parentheses, so we skip it.</p></li>
</ol>
<p>Now we're sitting on a P*bQ machine. (Note that our placeholders P and Q are just concatenation machines.) We replace the P edge with the NFA for b|a, and replace the Q edge with the NFA for a|b via recursive application of the above steps.</p>
<hr>
<p><em>Building P</em></p>
<ol>
<li><p>Skip. No parens.</p></li>
<li><p>Skip. No Kleene stars.</p></li>
<li><p>Skip. No contatenation.</p></li>
<li><p>Build the alternation machine for b|a. Intermediate result:<br>
<img src="https://i.stack.imgur.com/I8WX7.png" alt="NFA for b or a"></p></li>
</ol>
<hr>
<p><em>Integrating P</em></p>
<p>Next, we go back to that P*bQ machine and we tear out the P edge. We have the <em>source of the P edge</em> serve as the starting state for the P machine, and the <em>destination of the P edge</em> serve as the destination state for the P machine. We also make that state reject (take away its property of being an accept state). The result looks like this:<br>
<img src="https://i.stack.imgur.com/HVtwW.png" alt="enter image description here"></p>
<hr>
<p><em>Building Q</em></p>
<ol>
<li><p>Skip. No parens.</p></li>
<li><p>Skip. No Kleene stars.</p></li>
<li><p>Skip. No contatenation.</p></li>
<li><p>Build the alternation machine for a|b. Incidentally, alternation is commutative, so a|b is logically equivalent to b|a. (Read: skipping this minor footnote diagram out of laziness.)</p></li>
</ol>
<hr>
<p><em>Integrating Q</em></p>
<p>We do what we did with P above, except replacing the Q edge with the intermedtae b|a machine we constructed. This is the result:<br>
<img src="https://i.stack.imgur.com/YcqIF.png" alt="enter image description here"></p>
<p>Tada! Er, I mean, QED.</p>
<hr>
<p><strong>Want to know more?</strong></p>
<p>All the images above were generated using <a href="http://hackingoff.com/compilers/regular-expression-to-nfa-dfa" rel="noreferrer">an online tool for automatically converting regular expressions to non-deterministic finite automata</a>. You can find its <a href="https://github.com/hackingoff/scanner-generator/blob/master/lib/scanner_generator/thompson_construction.rb" rel="noreferrer">source code for the Thompson-McNaughton-Yamada Construction algorithm</a> online.</p>
<p>The algorithm is also addressed in <a href="https://rads.stackoverflow.com/amzn/click/com/0201100886" rel="noreferrer" rel="nofollow noreferrer">Aho's Compilers: Principles, Techniques, and Tools</a>, though its explanation is sparse on implementation details. You can also learn from <a href="http://swtch.com/~rsc/regexp/nfa.c.txt" rel="noreferrer">an implementation of the Thompson Construction in C</a> by the excellent Russ Cox, who described it some detail in a popular article about <a href="http://swtch.com/~rsc/regexp/regexp1.html" rel="noreferrer">regular expression matching</a>.</p> |
4,037,853 | Thread-safe copy constructor/assignment operator | <p>Let's say that we want to make class <code>A</code> thread-safe using an <code>std::mutex</code>. I am having my copy constructor and assignment operator similarly to the code below:</p>
<pre><code>#include <mutex>
class A {
private:
int i;
mutable std::mutex mtx;
public:
A() : i(), mtx() { }
A(const A& other) : i(), mtx()
{
std::lock_guard<std::mutex> _lock(other.mtx);
i = other.i;
}
A& operator=(const A& other)
{
if (this!=&other) {
std::lock_guard<std::mutex> _mylock(mtx), _otherlock(other.mtx);
i = other.i;
}
return *this;
}
int get() const
{
std::lock_guard<std::mutex> _mylock(mtx);
return i;
}
};
</code></pre>
<p>I do not think that it has any problems, other than the possibility of <code>other</code> to be destroyed by another thread before being copied, which I can deal with.</p>
<p>My issue is that I haven't seen this pattern anywhere, so I do not know if people just haven't had a need for that or that it is plainly wrong for reasons I currently don't see.</p>
<p>Thanks</p>
<p><strong>NOTES</strong>: </p>
<p>This is just an example. I can have an arbitrary number of member variables of any type, it does not have to be just an <code>int</code>.</p>
<p>After Martin York's comment for possible deadlocking, this is an updated version that uses copy-and-swap (copy elision is also possible, but it wouldn't handle efficiently the self-assignment case). </p>
<p>I also changed int to T, so people cannot assume that it is a POD.</p>
<pre><code>template<typename T>
class A {
private:
T t;
mutable std::mutex mtx;
public:
A() : t(), mtx() { }
A(const A& other) : t(), mtx()
{
std::lock_guard<std::mutex> _lock(other.mtx);
t = other.t;
}
A& operator=(const A& other)
{
if (this!=&other) {
A tmp(other);
std::lock_guard<std::mutex> _lock(mtx);
std::swap(t, tmp.t);
}
return *this;
}
T get() const
{
std::lock_guard<std::mutex> _lock(mtx);
return t;
}
};
</code></pre> | 20,571,338 | 5 | 7 | null | 2010-10-27 21:25:37.913 UTC | 9 | 2015-03-03 17:38:17.68 UTC | 2013-12-13 15:25:42.237 UTC | null | 487,362 | null | 487,362 | null | 1 | 8 | c++|c++11|thread-safety | 8,255 | <p>Old question, new answer:</p>
<p>Imho, a better way to deal with the dead-lock problem of the original copy assignment operator is:</p>
<pre><code> A& operator=(const A& other)
{
if (this!=&other) {
std::unique_lock<std::mutex> _mylock(mtx, std::defer_lock),
_otherlock(other.mtx, std::defer_lock);
std::lock(_mylock, _otherlock);
i = other.i;
}
return *this;
}
</code></pre>
<p>I.e. use <code>std::lock(L1, L2)</code> to simultaneously lock the two mutexes without fear of deadlock. This is likely to be higher performance than the copy/swap idiom, especially if the member data consists of <code>std::vector</code>, <code>std::string</code>, or types that contain vectors and/or strings.</p>
<p>In C++1y (we hope y is 4), there is a new <code><shared_mutex></code> header providing read/write lock capability which <em>may</em> provide a performance boost (performance testing would be necessary for specific use cases to confirm that). Here is how it would be used:</p>
<pre><code>#include <mutex>
#include <shared_mutex>
class A {
private:
int i;
mutable std::shared_mutex mtx;
public:
A() : i(), mtx() { }
A(const A& other) : i(), mtx()
{
std::shared_lock<std::shared_mutex> _lock(other.mtx);
i = other.i;
}
A& operator=(const A& other)
{
if (this!=&other) {
std::unique_lock<std::shared_mutex> _mylock(mtx, std::defer_lock);
std::shared_lock<std::shared_mutex> _otherlock(other.mtx, std::defer_lock);
std::lock(_mylock, _otherlock);
i = other.i;
}
return *this;
}
int get() const
{
std::shared_lock<std::shared_mutex> _mylock(mtx);
return i;
}
};
</code></pre>
<p>I.e. this is very similar to the original code (modified to use <code>std::lock</code> as I've done above). But the member mutex type is now <code>std::shared_mutex</code> instead of <code>std::mutex</code>. And when protecting a <code>const A</code> (and assuming no mutable members besides the mutex), one need only lock the mutex in "shared mode". This is easily done using <code>shared_lock<shared_mutex></code>. When you need to lock the mutex in "exclusive mode", you can use <code>unique_lock<shared_mutex></code>, or <code>lock_guard<shared_mutex></code> as appropriate, and in the same manner as you would have used this facilities with <code>std::mutex</code>.</p>
<p>In particular note that now many threads can simultaneously copy construct from the same <code>A</code>, or even copy assign <em>from</em> the same <code>A</code>. But only one thread can still copy assign <strong>to</strong> the same <code>A</code> at a time.</p> |
3,411,317 | CSS: height- fill out rest of div? | <p>i wonder if this is possible with simple css or if i have to use javascript for this?</p>
<p>i have a sidebar on my website. a simple div#sidbar it's normally about 1024px high, but the height changes dynamically due to it's content.</p>
<p>so let's imaginge the following case:</p>
<pre><code><div id="sidebar">
<div class="widget"></div> //has a height of 100px
<div class="widget"></div> //has a height of 100px
<div id="rest"></div> //this div should have the rest height till to the bottom of the sidebar
</div>
</code></pre>
<p>i want the div#rest to fill out the rest of the sidebar till it reaches the bottom of the div#sidebar.</p>
<p>is this possible with pure css?</p> | 3,411,371 | 7 | 0 | null | 2010-08-05 02:23:35.717 UTC | 2 | 2020-04-05 15:36:15.457 UTC | null | null | null | null | 1,444,475 | null | 1 | 35 | css|height | 58,770 | <p>What you want is something like <code>100% - 200px</code> but CSS doesn't support expressions such as these. IE has a non-standard "expressions" feature, but if you want your page to work on all browsers, I can't see a way to do this without JavaScript. Alternatively, you could make all the <code>div</code>s use percentage heights, so you could have something like 10%-10%-80%.</p>
<p><strong>Update:</strong> Here's a simple solution using JavaScript. Whenever the content in your sidebar changes, just call this function:</p>
<pre><code>function resize() {
// 200 is the total height of the other 2 divs
var height = document.getElementById('sidebar').offsetHeight - 200;
document.getElementById('rest').style.height = height + 'px';
};
</code></pre> |
3,378,560 | How to disable GCC warnings for a few lines of code | <p>In Visual C++, it's possible to use <a href="https://msdn.microsoft.com/en-us/library/2c8f766e.aspx" rel="noreferrer"><code>#pragma warning (disable: ...)</code></a>. Also I found that in GCC you can <a href="http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas" rel="noreferrer">override per file compiler flags</a>. How can I do this for "next line", or with push/pop semantics around areas of code using GCC?</p> | 3,394,268 | 9 | 4 | null | 2010-07-31 14:41:39.997 UTC | 86 | 2022-09-19 10:50:25.823 UTC | 2018-11-15 22:41:43.087 UTC | null | 149,482 | null | 149,482 | null | 1 | 286 | c|gcc|compiler-warnings|pragma | 188,107 | <p>It appears this <a href="http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html" rel="nofollow noreferrer">can be done</a>. I'm unable to determine the version of GCC that it was added, but it was sometime before June 2010.</p>
<p>Here's an example:</p>
<pre><code>#pragma GCC diagnostic error "-Wuninitialized"
foo(a); /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
foo(b); /* no diagnostic for this one */
#pragma GCC diagnostic pop
foo(c); /* error is given for this one */
#pragma GCC diagnostic pop
foo(d); /* depends on command line options */
</code></pre> |
3,718,383 | Why should a Java class implement comparable? | <p>Why is Java <code>Comparable</code> used? Why would someone implement <code>Comparable</code> in a class? What is a real life example where you need to implement comparable?</p> | 3,718,515 | 10 | 2 | null | 2010-09-15 14:04:04.977 UTC | 54 | 2020-02-27 07:06:06.933 UTC | 2016-01-27 12:36:44.307 UTC | null | 584,674 | null | 282,383 | null | 1 | 146 | java | 275,512 | <p>Here is a real life sample. Note that <code>String</code> also implements <code>Comparable</code>.</p>
<pre><code>class Author implements Comparable<Author>{
String firstName;
String lastName;
@Override
public int compareTo(Author other){
// compareTo should return < 0 if this is supposed to be
// less than other, > 0 if this is supposed to be greater than
// other and 0 if they are supposed to be equal
int last = this.lastName.compareTo(other.lastName);
return last == 0 ? this.firstName.compareTo(other.firstName) : last;
}
}
</code></pre>
<p>later..</p>
<pre><code>/**
* List the authors. Sort them by name so it will look good.
*/
public List<Author> listAuthors(){
List<Author> authors = readAuthorsFromFileOrSomething();
Collections.sort(authors);
return authors;
}
/**
* List unique authors. Sort them by name so it will look good.
*/
public SortedSet<Author> listUniqueAuthors(){
List<Author> authors = readAuthorsFromFileOrSomething();
return new TreeSet<Author>(authors);
}
</code></pre> |
3,786,774 | In c# what does 'where T : class' mean? | <p>In C# what does <code>where T : class</code> mean? </p>
<p>Ie. </p>
<pre><code>public IList<T> DoThis<T>() where T : class
</code></pre> | 3,786,790 | 10 | 0 | null | 2010-09-24 11:55:16.477 UTC | 30 | 2022-08-19 17:43:59.223 UTC | 2010-09-24 12:33:05.853 UTC | null | 428,789 | null | 57,731 | null | 1 | 161 | c#|syntax | 144,817 | <p>Simply put this is constraining the generic parameter to a class (or more specifically a reference type which could be a class, interface, delegate, or array type). </p>
<p>See this <a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" rel="noreferrer">MSDN article</a> for further details.</p> |
3,368,555 | Editing screenshots in iTunes Connect after iOS app was approved | <p>In the iTunes Connect App Management interface -- how do I edit the screenshots for my localized (approved and live) iPhone app?</p>
<p>Unfortunately, the web upload form had a bug which actually required the screenshots to be provided in reverse order (I provided them in the correct order, which meant that Apple reversed them and now they ended up wrong). <a href="https://stackoverflow.com/questions/1914875/order-of-additional-screenshots-when-submitting-app-in-itunes-connect">Also mentioned here at StackOverflow</a>. I only managed to edit the 4 screenshots in the US version, but not my localized version, and that was in the old interface.</p> | 3,393,650 | 11 | 1 | null | 2010-07-30 03:33:32.2 UTC | 16 | 2019-05-28 00:18:32.8 UTC | 2019-05-28 00:18:32.8 UTC | null | 1,033,581 | null | 34,170 | null | 1 | 96 | ios|app-store-connect | 94,000 | <p>Apple support now got back with the (somehow not too satisfactory) answer:</p>
<blockquote>
<p>If your app is currently for sale on
the App Store, you will need to submit
an update in order to change your app
screenshots.</p>
<p>If you have any further questions
regarding this, please let us know.</p>
</blockquote> |
7,730,502 | Will main() catch exceptions thrown from threads? | <p>I have a pretty large application that dynamically loads shared objects and executes code in the shared object. As a precaution, I put a try/catch around almost everything in <code>main</code>. I created a catch for 3 things: <code>myException</code> (an in house exception), <code>std::exception</code>, and <code>...</code> (catch all exceptions).</p>
<p>As part of the shared objects execution, many <code>pthreads</code> are created. When a thread throws an exception, it is not caught by <code>main</code>. Is this the standard behavior? How can I catch all exceptions, no matter what thread they are thrown from?</p> | 7,730,517 | 4 | 0 | null | 2011-10-11 18:11:43.91 UTC | 13 | 2018-09-19 12:52:33.91 UTC | 2018-09-19 12:52:33.91 UTC | null | 1,971,003 | null | 562,697 | null | 1 | 47 | c++|exception-handling|pthreads | 40,137 | <blockquote>
<p>Will main() catch exceptions thrown from threads?</p>
</blockquote>
<p>No</p>
<blockquote>
<p>When a thread throws an exception, it is not caught by main. Is this the standard behavior?</p>
</blockquote>
<p>Yes, this is standard behaviour.</p>
<p>To catch an exception originating in thread <code>X</code>, you have to have the <code>try</code>-<code>catch</code> clause in thread <code>X</code> (for example, around everything in the thread function, similarly to what you already do in <code>main</code>).</p>
<p>For a related question, see <a href="https://stackoverflow.com/questions/233127/how-can-i-propagate-exceptions-between-threads">How can I propagate exceptions between threads?</a></p> |
8,289,100 | Create unique constraint with null columns | <p>I have a table with this layout:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE Favorites (
FavoriteId uuid NOT NULL PRIMARY KEY,
UserId uuid NOT NULL,
RecipeId uuid NOT NULL,
MenuId uuid
);
</code></pre>
<p>I want to create a unique constraint similar to this:</p>
<pre><code>ALTER TABLE Favorites
ADD CONSTRAINT Favorites_UniqueFavorite UNIQUE(UserId, MenuId, RecipeId);
</code></pre>
<p>However, this will allow multiple rows with the same <code>(UserId, RecipeId)</code>, if <code>MenuId IS NULL</code>. I want to allow <code>NULL</code> in <code>MenuId</code> to store a favorite that has no associated menu, but I only want at most one of these rows per user/recipe pair.</p>
<p>The ideas I have so far are:</p>
<ol>
<li><p>Use some hard-coded UUID (such as all zeros) instead of null.<br />
However, <code>MenuId</code> has a FK constraint on each user's menus, so I'd then have to create a special "null" menu for every user which is a hassle.</p>
</li>
<li><p>Check for existence of a null entry using a trigger instead.<br />
I think this is a hassle and I like avoiding triggers wherever possible. Plus, I don't trust them to guarantee my data is never in a bad state.</p>
</li>
<li><p>Just forget about it and check for the previous existence of a null entry in the middle-ware or in a insert function, and don't have this constraint.</p>
</li>
</ol>
<p>I'm using Postgres 9.0. Is there any method I'm overlooking?</p> | 8,289,253 | 4 | 2 | null | 2011-11-27 21:16:12.893 UTC | 88 | 2022-08-17 21:18:24.503 UTC | 2022-06-03 22:14:24.537 UTC | null | 939,860 | null | 392,044 | null | 1 | 326 | sql|postgresql|database-design|null|referential-integrity | 142,234 | <h3>Postgres 15 or newer</h3>
<p>Postgres 15 (currently beta) adds the clause <strong><code>NULLS NOT DISTINCT</code></strong>. <a href="https://www.postgresql.org/docs/15/release-15.html#id-1.11.6.5.5.3.4" rel="noreferrer">The release notes:</a></p>
<blockquote>
<ul>
<li><p>Allow unique constraints and indexes to treat NULL values as not distinct (Peter Eisentraut)</p>
<p>Previously NULL values were always indexed as distinct values, but
this can now be changed by creating constraints and indexes using
<code>UNIQUE NULLS NOT DISTINCT</code>.</p>
</li>
</ul>
</blockquote>
<p>With this clause <code>NULL</code> is treated like just another value, and a <a href="https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS" rel="noreferrer"><code>UNIQUE</code> constraint</a> does not allow more than one row with the same <code>NULL</code> value. The task is simple now:</p>
<pre><code>ALTER TABLE favorites
ADD CONSTRAINT favo_uni UNIQUE NULLS NOT DISTINCT (user_id, menu_id, recipe_id);
</code></pre>
<p>There are examples in the manual chapter <a href="https://www.postgresql.org/docs/15/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS" rel="noreferrer"><em>"Unique Constraints"</em></a>.<br />
The clause switches behavior for <em>all</em> index keys. You can't treat <code>NULL</code> as equal for one key, but not for another.<br />
<code>NULLS DISTINCT</code> remains the default (in line with standard SQL) and does not have to be spelled out.</p>
<p>The same clause works for a <a href="https://www.postgresql.org/docs/15/sql-createindex.html" rel="noreferrer"><code>UNIQUE</code> index</a>, too:</p>
<pre><code>CREATE UNIQUE INDEX favo_uni_idx
ON favorites (user_id, menu_id, recipe_id) NULLS NOT DISTINCT;
</code></pre>
<p>Note the position of the new clause <em>after</em> the key fields.</p>
<h3>Postgres 14 or older</h3>
<p>Create <a href="https://www.postgresql.org/docs/current/indexes-partial.html" rel="noreferrer"><strong>two partial indexes</strong></a>:</p>
<pre><code>CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;
CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;
</code></pre>
<p>This way, there can only be one combination of <code>(user_id, recipe_id)</code> where <code>menu_id IS NULL</code>, effectively implementing the desired constraint.</p>
<p>Possible drawbacks:</p>
<ul>
<li>You cannot have a foreign key referencing <code>(user_id, menu_id, recipe_id)</code>. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead!)</li>
<li>You cannot base <code>CLUSTER</code> on a partial index.</li>
<li>Queries without a matching <code>WHERE</code> condition cannot use the partial index.</li>
</ul>
<p>If you need a <em>complete</em> index, you can alternatively drop the <code>WHERE</code> condition from <code>favo_3col_uni_idx</code> and your requirements are still enforced.<br />
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of <code>NULL</code> values, this may or may not be useful. In extreme situations it may even help to maintain all three indexes (the two partial ones and a total on top).</p>
<p>This is a good solution for a <strong>single nullable column</strong>, maybe for two. But it gets out of hands quickly for more as you need a separate partial index for every combination of nullable columns, so the number grows binomially. For <strong>multiple nullable columns</strong>, see instead:</p>
<ul>
<li><a href="https://dba.stackexchange.com/a/299107/3684">Why doesn't my UNIQUE constraint trigger?</a></li>
</ul>
<p>Aside: I advise not to use <a href="https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS" rel="noreferrer">mixed case identifiers in PostgreSQL</a>.</p> |
8,093,099 | ARC forbids Objective-C objects in structs or unions despite marking the file -fno-objc-arc | <p>ARC forbids Objective-C objects in structs or unions despite marking the file -fno-objc-arc?
Why is this so?</p>
<p>I had the assumption that if you mark it -fno-objc-arc you don't have this restriction.</p> | 8,357,620 | 4 | 0 | null | 2011-11-11 11:09:04.643 UTC | 18 | 2018-10-10 04:18:17.61 UTC | 2011-11-11 22:05:14.117 UTC | user557219 | null | null | 429,763 | null | 1 | 85 | iphone|objective-c|struct|ios5|automatic-ref-counting | 53,182 | <p>If you got this message try __unsafe_unretained. It is only safe, if the objects in the struct are unretained.
Example: If you use OpenFeint with ARC the Class OFBragDelegateStrings says this error in a struct.</p>
<pre><code>typedef struct OFBragDelegateStrings
{
NSString* prepopulatedText;
NSString* originalMessage;
} OFBragDelegateStrings;
</code></pre>
<p>to</p>
<pre><code>typedef struct OFBragDelegateStrings
{
__unsafe_unretained NSString* prepopulatedText;
__unsafe_unretained NSString* originalMessage;
} OFBragDelegateStrings;
</code></pre> |
7,781,893 | EF Code First: How to get random rows | <p>How can I build a query where I would retrieve random rows?</p>
<p>If I were to write it in SQL then I would put an order by on newid() and chop off n number of rows from the top. Anyway to do this in EF code first? </p>
<p>I have tried creating a query that uses newid() and executing it using DbSet.SqlQuery(). while it works, its not the cleanest of solutions. </p>
<p>Also, tried retrieve all the rows and sorting them by a new guid. Although the number of rows are fairly small, its still not a good solution.</p>
<p>Any ideas?</p> | 7,781,899 | 4 | 2 | null | 2011-10-16 02:07:18.203 UTC | 13 | 2022-08-01 05:09:28.12 UTC | null | null | null | null | 642,269 | null | 1 | 91 | c#|entity-framework|entity-framework-4.1|ef-code-first | 40,519 | <p>Just call:</p>
<pre><code>something.OrderBy(r => Guid.NewGuid()).Take(5)
</code></pre> |
4,745,112 | JavaScript regex for alphanumeric string with length of 3-5 chars | <p>I need regex for validating alphanumeric String with length of 3-5 chars. I tried following regex found from the web, but it didn't even catch alphanumerics correctly. </p>
<pre><code>var myRegxp = /^([a-zA-Z0-9_-]+)$/;
if(myRegxp.test(value) == false)
{
return false;
}
</code></pre> | 4,745,130 | 3 | 2 | null | 2011-01-20 08:58:24.917 UTC | 6 | 2017-07-02 13:38:55.04 UTC | null | null | null | null | 159,793 | null | 1 | 30 | javascript|regex | 117,051 | <p>add <code>{3,5}</code> to your expression which means length between 3 to 5</p>
<pre><code>/^([a-zA-Z0-9_-]){3,5}$/
</code></pre> |
4,734,846 | calling operators of base class... safe? | <p>Is following pattern ok/safe ? Or are there any shortcomings ?
(I also use it for equality operators)</p>
<pre><code>Derived& operator=(const Derived& rhs)
{
static_cast<Base&>(*this) = rhs;
// ... copy member variables of Derived
return *this;
}
</code></pre> | 4,734,889 | 3 | 0 | null | 2011-01-19 11:46:50.663 UTC | 4 | 2015-11-25 14:58:45.543 UTC | 2011-01-19 11:56:21.58 UTC | null | 231,717 | null | 231,717 | null | 1 | 35 | c++|operators | 31,868 | <p>This is fine, but it's a lot more readable IMHO to call the base-class by name:</p>
<pre><code>Base::operator = (rhs);
</code></pre> |
4,113,397 | Working with single page websites and maintaining state using a URL hash and jQuery | <p>I'm working on my portfolio, making it entirely jQuery based. So my problem is when you go to a page, then refresh then it will take you to the home page again. So I have two questions, actually.</p>
<ol>
<li>How do you (via jQuery/Javascript) get a "hash code" from the url?
<ol>
<li>E.G. I want the bold part of this: <a href="http://portfolio.theadamgaskins.com/Portfolio/" rel="nofollow noreferrer">http://portfolio.theadamgaskins.com/Portfolio/</a><strong>#graphicsDesign</strong></li>
</ol></li>
<li>How do you change the url in the address bar when you navigate to a new page to contain the hash code for that page?
<ol>
<li>E.G. when you go the the graphicsDesign page, the link in the address bar changes to <a href="http://portfolio.theadamgaskins.com/Portfolio/#graphicsDesign" rel="nofollow noreferrer">http://portfolio.theadamgaskins.com/Portfolio/#graphicsDesign</a></li>
</ol></li>
</ol> | 4,113,412 | 4 | 3 | null | 2010-11-06 14:03:54.973 UTC | 11 | 2013-04-16 04:37:38.44 UTC | 2013-04-16 04:37:38.44 UTC | null | 59,730 | null | 481,702 | null | 1 | 12 | jquery|url|hash | 46,776 | <p>You make the anchor point to an internal link like so:</p>
<pre><code><a href="#graphicsDesign">Graphics</a>
</code></pre>
<p>And then simply make jQuery respond to the click event and let the browser follow the internal link naturally. The browser should now have the internal link in it's address bar. You can use the following JavaScript to parse <a href="https://stackoverflow.com/questions/4113397/jquery-url-hash/4113412#4113412">the URL</a> and then load the correct part of the HTML document. You will need to write the code so that the correct content is loaded based off what the browsers internal address is.</p>
<pre><code>if(window.location.hash === "graphicsDesign" ||
window.location.hash === "somethingElse") {
loadContent(window.location.hash);
}
</code></pre> |
4,699,381 | Best Way to Inject Hibernate Session by Spring 3 | <p>I am not sure whats the best way to inject Hibernate's session instance to DAO classes using Spring3. I am not using Spring's Hibernate Template support for this so here is the code i have in the DAO class.</p>
<pre><code>public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory=sessionFactory;
}
public SessionFactory getSessionFactory(){
log.info("Returning a refrence to the session instance");
if(sessionFactory==null){
log.error("Not able to find any associated session");
throw new RuntimeException("Not able to find any associated session");
}
return sessionFactory;
}
</code></pre>
<p>Below is the code for injecting session in to this method</p>
<pre><code><bean id="genericSessionFactory" class="HibernateSessionFactory"
factory-method="getSessionfactory" scope="prototype/>
</code></pre>
<p>I am not sure if this is the best way to do SessionFactory injection since we don't want to use Spring Template for our project.
So any other suggestion for improvement will be much helpfull.</p> | 4,699,514 | 4 | 2 | null | 2011-01-15 11:42:01.163 UTC | 17 | 2015-04-22 13:02:08.15 UTC | 2015-04-22 13:02:08.15 UTC | null | 169,534 | null | 471,607 | null | 1 | 21 | java|hibernate|spring | 54,383 | <p>The <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-hibernate-straight" rel="noreferrer">Spring Reference suggests this usage</a>:</p>
<pre><code>public class ProductDaoImpl implements ProductDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Collection loadProductsByCategory(String category) {
return this.sessionFactory.getCurrentSession()
.createQuery(
"from test.Product product where product.category=?")
.setParameter(0, category)
.list();
}
}
</code></pre>
<p>That way your classes don't have any dependencies to Spring, you just use plain Hibernate.</p> |
4,406,481 | Financial technical analysis in python | <p>Do you know if there is any financial technical analysis module available for python ? Need to calculate various indicators such as RSI, EMA, DEMA etc for a project</p> | 4,406,666 | 4 | 0 | null | 2010-12-10 07:04:58.413 UTC | 63 | 2021-03-23 09:11:11.74 UTC | 2020-01-10 20:59:49.793 UTC | null | -1 | null | 415,088 | null | 1 | 62 | python|finance | 47,274 | <p>Here are a few thoughts... I have only used Numpy, Scipy, and Matplotlib for financial calculations.</p>
<ul>
<li><a href="http://www.advogato.org/proj/py-fi/" rel="noreferrer">py-fi</a> - very basic financial functions</li>
<li><a href="https://code.google.com/p/fin2py/" rel="noreferrer">fin2py</a> - financial tools</li>
<li><a href="http://www.scipy.org" rel="noreferrer">Numpy/Scipy</a> - covers all of the statistics basics</li>
<li><a href="http://matplotlib.sourceforge.net" rel="noreferrer">Matplotlib</a> - plotting financial functions</li>
<li><a href="http://rpy.sourceforge.net/" rel="noreferrer">RPy</a> - a Python interface to R allowing use of R libraries</li>
<li><a href="http://www.goldb.org/ystockquote.html" rel="noreferrer">ystockquote</a> - Python API for Yahoo! Stock Data</li>
<li><a href="http://quantlib.org" rel="noreferrer">QuantLib</a> - Open source library (supposedly has Python Bindings)</li>
<li><a href="http://code.google.com/p/pyfinancial/" rel="noreferrer">PyFinancial</a> - Docs in Spanish</li>
<li><a href="https://github.com/escheffel/pymaclab/" rel="noreferrer">PyMacLab</a> - "Series of classes useful for conducting research in dynamic macroeconomics"</li>
<li><a href="http://code.google.com/p/tsdb/" rel="noreferrer">TSDB</a> - for storing large volumes of time series data</li>
<li><a href="http://code.google.com/p/pyvol/" rel="noreferrer">PyVol</a> - volatility estimation of financial time series</li>
</ul> |
4,600,208 | Is memory allocation in linux non-blocking? | <p>I am curious to know if the allocating memory using a default new operator is a non-blocking operation.</p>
<p>e.g.</p>
<pre><code>struct Node {
int a,b;
};
</code></pre>
<p>...</p>
<pre><code>Node foo = new Node();
</code></pre>
<p>If multiple threads tried to create a new Node and if one of them was suspended by the OS in the middle of allocation, would it block other threads from making progress?</p>
<p>The reason why I ask is because I had a concurrent data structure that created new nodes. I then modified the algorithm to recycle the nodes. The throughput performance of the two algorithms was virtually identical on a 24 core machine. However, I then created an interference program that ran on all the system cores in order to create as much OS pre-emption as possible. The throughput performance of the algorithm that created new nodes decreased by a factor of 5 relative the algorithm that recycled nodes.</p>
<p>I'm curious to know why this would occur.</p>
<p>Thanks.</p>
<p>*Edit : pointing me to the code for the c++ memory allocator for linux would be helpful as well. I tried looking before posting this question, but had trouble finding it.</p> | 4,650,200 | 5 | 4 | null | 2011-01-05 01:59:49.963 UTC | 10 | 2020-08-26 22:01:50.103 UTC | 2020-08-26 22:01:50.103 UTC | null | 2,430,549 | null | 196,374 | null | 1 | 21 | c++|linux|multithreading|memory-management | 5,259 | <p>seems to me if your interference app were using new/delete (malloc/free), then the interference app's would interfere with the non recycle test more. But I don't know how your interference test is implemented. </p>
<p><strong>Depending on how you recycle (ie if you use pthread mutexes god forbid) your recycle code could be slow (gcc atomic ops would be 40x faster at implementing recycle).</strong> </p>
<p>Malloc, in some variation for a long time on at least some platforms, has been aware of threads. Use the compiler switches on gcc to be sure you get it. Newer algorithms maintain pools of small memory chunks for <em>each</em> thread, so there is no or little blocking if your thread has the small item available. I have over simplified this and it depends on what malloc your system is using. Plus, if you go and allocate millions of items to do a test....well then you wont see that effect, because the small item pools are limited in size. Or maybe you will. I don't know. If you freed the item right after allocating, you would be more likely to see it. Freed small items go back into the small item lists rather than the shared heap. Although "what happens when thread B frees an item allocated by thread A" is a problem that may or may not be dealt with on your version of malloc and may not be dealt with in a non blocking manner. For sure, if you didn't immediately free during a large test, then the the thread would have to refill its small item list many times. That can block if more than one thread tries. Finally, at some point your process' heap will ask the system for heap memory, which can obviously block. </p>
<p>So are you using small memory items? For your malloc I don't know what small would be, but if you are < 1k that is for sure small. Are you allocating and freeing one after the other, or allocating thousands of nodes and then freeing thousands of nodes? Was your interference app allocating? All of these things will affect the results. </p>
<p><strong>How to recycle with atomic ops (CAS = compare and swap):</strong></p>
<p>First add a pNextFreeNode to your node object. I used void*, you can use your type. This code is for 32 bit pointers, but works for 64 bit as well. Then make a global recycle pile.</p>
<pre><code>void *_pRecycleHead; // global head of recycle list.
</code></pre>
<p>Add to recycle pile:</p>
<pre><code>void *Old;
while (1) { // concurrency loop
Old = _pRecycleHead; // copy the state of the world. We operate on the copy
pFreedNode->pNextFreeNode = Old; // chain the new node to the current head of recycled items
if (CAS(&_pRecycleHead, Old, pFreedNode)) // switch head of recycled items to new node
break; // success
}
</code></pre>
<p>remove from pile:</p>
<pre><code>void *Old;
while (Old = _pRecycleHead) { // concurrency loop, only look for recycled items if the head aint null
if (CAS(&_pRecycleHead, Old, Old->pNextFreeNode)) // switch head to head->next.
break; // success
}
pNodeYoucanUseNow = Old;
</code></pre>
<p>Using CAS means the operation will succeed only if the item you are changing is the Old value you pass in. If there is a race and another thread got there first, then the old value will be different. In real life this race happens very very rarely. CAS is only slighlty slower than actually setting a value so compared to mutexes....it rocks.</p>
<p>The remove from pile, above, has a race condition if you add and remove the same item rapidly. We solve that by adding a version # to the CAS'able data. If you do the version # at the same time as the pointer to the head of the recycle pile you win. Use a union. Costs nothing extra to CAS 64 bits.</p>
<pre><code>union TRecycle {
struct {
int iVersion;
void *pRecycleHead;
} ; // we can set these. Note, i didn't name this struct. You may have to if you want ANSI
unsigned long long n64; // we cas this
}
</code></pre>
<p>Note, You will have to go to 128 bit struct for 64 bit OS. so the global recycle pile looks like this now:</p>
<pre><code>TRecycle _RecycleHead;
</code></pre>
<p>Add to recycle pile:</p>
<pre><code>while (1) { // concurrency loop
TRecycle New,Old;
Old.n64 = _RecycleHead.n64; // copy state
New.n64 = Old.n64; // new state starts as a copy
pFreedNode->pNextFreeNode = Old.pRecycleHead; // link item to be recycled into recycle pile
New.pRecycleHead = pFreedNode; // make the new state
New.iVersion++; // adding item to list increments the version.
if (CAS(&_RecycleHead.n64, Old.n64, New.n64)) // now if version changed...we fail
break; // success
}
</code></pre>
<p>remove from pile:</p>
<pre><code>while (1) { // concurrency loop
TRecycle New,Old;
Old.n64 = _RecycleHead.n64; // copy state
New.n64 = Old.n64; // new state starts as a copy
New.pRecycleHead = New.pRecycledHead.pNextFreeNode; // new will skip over first item in recycle list so we can have that item.
New.iVersion++; // taking an item off the list increments the version.
if (CAS(&_RecycleHead.n64, Old.n64, New.n64)) // we fail if version is different.
break; // success
}
pNodeYouCanUseNow = Old.pRecycledHead;
</code></pre>
<p>I bet if you recycle this way you will see a perf increase.</p> |
4,343,793 | How to disable highlighting on listbox but keep selection? | <p>I am having trouble finding how to not allow my ListBox to highlight the item selected. I know that I didn't add a trigger to highlight the item.</p>
<pre><code><ListBox Name="CartItems" ItemsSource="{Binding}"
ItemTemplate="{StaticResource TicketTemplate}"
Grid.Row="3" Grid.ColumnSpan="9" Background="Transparent"
BorderBrush="Transparent">
</ListBox>
</code></pre> | 8,975,226 | 7 | 0 | null | 2010-12-03 08:44:07.047 UTC | 12 | 2019-11-24 15:39:06.943 UTC | 2018-10-06 09:09:52.623 UTC | null | 1,506,454 | null | 216,408 | null | 1 | 40 | wpf|xaml|listbox | 46,621 | <p>Late answer, but there's a much better and simpler solution:</p>
<pre><code><ListBox>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</ListBox.Resources>
</ListBox>
</code></pre>
<p>This allows you to have a LisBox that looks just like an itemscontrol, but has support for selection.</p>
<p><strong>Edit:</strong> <em>How</em> it works<br/>
This alters "colors of the system", in other words your windows theme, only for this ListBox and its children (we actually want to target the <code>ListboxItem</code>).</p>
<p>For example hovering a <code>ListboxItem</code> usually gives it a deep blue background, but here we set it to transparent (HighlightBrushKey).</p>
<p><strong>Edit (30 June 2016):</strong><br/>
It seems for latest Windows version this is not enough anymore, you also need to redefine <code>InactiveSelectionHighlightBrushKey</code></p>
<pre><code><SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</code></pre>
<p>Thanks to @packoman in the comments</p> |
4,181,884 | :after and :before CSS pseudo elements hack for Internet Explorer 7 | <p>I am using <code>:after</code> and <code>:before</code> CSS pseudo elements and it is working fine in <strong>Internet Explorer 8</strong>, and all modern browsers but it is not working fine in <strong>Internet Explorer 7</strong>. Are there known hacks to work around this in <strong>Internet Explorer 7</strong>?</p> | 4,181,897 | 7 | 0 | null | 2010-11-15 06:14:00.76 UTC | 44 | 2021-12-11 10:49:43.067 UTC | 2021-12-11 10:49:43.067 UTC | null | 12,892,553 | null | 364,383 | null | 1 | 59 | html|css|internet-explorer-7|pseudo-element | 93,560 | <p>with any pure CSS hack it's not possible.</p>
<p>Use IE8.js <a href="http://code.google.com/p/ie7-js/" rel="noreferrer">http://code.google.com/p/ie7-js/</a></p>
<p>It has support for this. <a href="http://ie7-js.googlecode.com/svn/test/index.html" rel="noreferrer">http://ie7-js.googlecode.com/svn/test/index.html</a></p>
<p>test page also there </p>
<p>after - <a href="http://ie7-js.googlecode.com/svn/test/after.html" rel="noreferrer">http://ie7-js.googlecode.com/svn/test/after.html</a></p>
<p>before - <a href="http://ie7-js.googlecode.com/svn/test/before.html" rel="noreferrer">http://ie7-js.googlecode.com/svn/test/before.html</a></p>
<p><strong>Edit after 1st comment</strong></p>
<p>You can just keep this js for IE6 and 7. other browser will not read it.</p>
<pre><code><!--[if lt IE 8]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>
<![endif]-->
</code></pre>
<p>And if you are already using jQuery in your project than you can use this plugin</p>
<p><strong>jQuery Pseudo Plugin</strong></p>
<p><a href="http://jquery.lukelutman.com/plugins/pseudo/" rel="noreferrer">http://jquery.lukelutman.com/plugins/pseudo/</a></p> |
4,808,329 | Can I call a view from within another view? | <p>One of my view needs to add an item, along with other functionality, but I already have another view which specifically adds an item. </p>
<p>Can I do something like:</p>
<pre><code>def specific_add_item_view(request):
item = Item.objects.create(foo=request.bar)
def big_view(request):
# ...
specific_add_item_view(request)
</code></pre> | 4,808,403 | 7 | 1 | null | 2011-01-26 18:22:04.797 UTC | 24 | 2022-04-14 11:10:25.683 UTC | null | null | null | null | 159,685 | null | 1 | 89 | django|django-views | 106,469 | <p>View functions should return a rendered HTML back to the browser (in an <code>HttpResponse</code>). Calling a view within a view means that you're (potentially) doing the rendering twice. Instead, just factor out the "add" into another function that's not a view, and have both views call it. </p>
<pre><code>def add_stuff(bar):
item = Item.objects.create(foo=bar)
return item
def specific_add_item_view(request):
item = add_stuff(bar)
...
def big_view(request):
item = add_stuff(bar)
...
</code></pre> |
4,166,966 | What is the point of the diamond operator (<>) in Java? | <p>The diamond operator in java 7 allows code like the following:</p>
<pre><code>List<String> list = new LinkedList<>();
</code></pre>
<p>However in Java 5/6, I can simply write:</p>
<pre><code>List<String> list = new LinkedList();
</code></pre>
<p>My understanding of type erasure is that these are exactly the same. (The generic gets removed at runtime anyway). </p>
<p>Why bother with the diamond at all? What new functionality / type safety does it allow? If it doesn't yield any new functionality why do they mention it as a feature? Is my understanding of this concept flawed?</p> | 4,167,148 | 7 | 5 | null | 2010-11-12 16:43:23.82 UTC | 140 | 2021-07-15 00:03:26.467 UTC | 2021-07-15 00:03:26.467 UTC | null | 68,587 | null | 470,062 | null | 1 | 485 | java|generics|java-7|diamond-operator | 165,925 | <p>The issue with</p>
<pre><code>List<String> list = new LinkedList();
</code></pre>
<p>is that on the left hand side, you are using the <em>generic</em> type <code>List<String></code> where on the right side you are using the <em>raw</em> type <code>LinkedList</code>. Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless
you absolutely have to.</p>
<p>Now, if Java had generics from the beginning and didn't have types, such as <code>LinkedList</code>, that were originally created before it had generics, it probably could have made it so that the constructor for a generic type automatically infers its type parameters from the left-hand side of the assignment if possible. But it didn't, and it must treat raw types and generic types differently for backwards compatibility. That leaves them needing to make a <em>slightly different</em>, but equally convenient, way of declaring a new instance of a generic object without having to repeat its type parameters... the diamond operator.</p>
<p>As far as your original example of <code>List<String> list = new LinkedList()</code>, the compiler generates a warning for that assignment because it must. Consider this:</p>
<pre><code>List<String> strings = ... // some list that contains some strings
// Totally legal since you used the raw type and lost all type checking!
List<Integer> integers = new LinkedList(strings);
</code></pre>
<p>Generics exist to provide compile-time protection against doing the wrong thing. In the above example, using the raw type means you don't get this protection and will get an error at runtime. This is why you should not use raw types.</p>
<pre><code>// Not legal since the right side is actually generic!
List<Integer> integers = new LinkedList<>(strings);
</code></pre>
<p>The diamond operator, however, allows the right hand side of the assignment to be defined as a true generic instance with the same type parameters as the left side... without having to type those parameters again. It allows you to keep the safety of generics with <em>almost</em> the same effort as using the raw type.</p>
<p>I think the key thing to understand is that raw types (with no <code><></code>) cannot be treated the same as generic types. When you declare a raw type, you get none of the benefits and type checking of generics. You also have to keep in mind that <em>generics are a general purpose part of the Java language</em>... they don't just apply to the no-arg constructors of <code>Collection</code>s!</p> |
4,668,619 | How do I filter query objects by date range in Django? | <p>I've got a field in one model like:</p>
<pre><code>class Sample(models.Model):
date = fields.DateField(auto_now=False)
</code></pre>
<p>Now, I need to filter the objects by a date range.</p>
<p>How do I filter all the objects that have a date between <code>1-Jan-2011</code> and <code>31-Jan-2011</code>?</p> | 4,668,718 | 8 | 0 | null | 2011-01-12 12:09:58.617 UTC | 90 | 2022-02-08 12:13:14.94 UTC | 2019-04-21 15:33:08.637 UTC | null | 5,250,453 | null | 469,652 | null | 1 | 348 | python|django|django-models|django-queryset | 425,546 | <p>Use </p>
<pre><code>Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])
</code></pre>
<p>Or if you are just trying to filter month wise: </p>
<pre><code>Sample.objects.filter(date__year='2011',
date__month='01')
</code></pre>
<h3>Edit</h3>
<p>As Bernhard Vallant said, if you want a queryset which excludes the <code>specified range ends</code> you should consider <a href="https://stackoverflow.com/questions/4668619/django-database-query-how-to-filter-objects-by-date-range/4668703#4668703">his solution</a>, which utilizes gt/lt (greater-than/less-than).</p> |
4,662,180 | C# public variable as writeable inside the class but readonly outside the class | <p>I have a .Net C# class where I need to make a variable public. I need to initialize this variable within a method (not within the constructor). However, I don't want the variable to be modifieable by other classes. Is this possible?</p> | 4,662,190 | 9 | 1 | null | 2011-01-11 20:19:12.273 UTC | 4 | 2020-08-31 17:12:12.433 UTC | 2013-08-29 16:15:43.45 UTC | null | 96,780 | null | 368,259 | null | 1 | 49 | c#|variables|public | 28,517 | <p>Don't use a field - use a property:</p>
<pre><code>class Foo
{
public string Bar { get; private set; }
}
</code></pre>
<p>In this example <code>Foo.Bar</code> is readable everywhere and writable only by members of <code>Foo</code> itself.</p>
<p>As a side note, this example is using a C# feature introduced in version 3 called <em>automatically implemented properties</em>. This is syntactical sugar that the compiler will transform into a regular property that has a private backing field like this:</p>
<pre><code>class Foo
{
[CompilerGenerated]
private string <Bar>k__BackingField;
public string Bar
{
[CompilerGenerated]
get
{
return this.<Bar>k__BackingField;
}
[CompilerGenerated]
private set
{
this.<Bar>k__BackingField = value;
}
}
}
</code></pre> |
4,782,543 | Integrating the ZXing library directly into my Android application | <p>I'm writing this in mere desperation :) I've been assigned to make a standalone barcode scanner (as a proof of concept) to an Android 1.6 phone.</p>
<p>For this i've discovered the ZXing library.</p>
<p>I've googled, read related topics here on StackOverflow used common sence and so forth. Nothing seemed to have helped, and i just can't punch a hole on this mentale blockade :/</p>
<p>I know it to be possible, to use the lib, and create your own standalone barcode scanner. I've read that using the "Barcode Scanner" provided by the Zxing folks, is by far the easiest solution (via Intent). Unfortunately this is not an option, and a standalone app is desired.</p>
<p>So to sum up my problem :</p>
<ol>
<li>How to integrate ZXing source lib into my Android Code project through Eclipse?</li>
<li>When integrated ... how to make use of the lib, to "load" the scanning function?</li>
<li>A step to step guide is almost prefered because i just started working in Eclipse.</li>
</ol>
<p>I've tried to make my code project dependant of the Android folder from the ZXing source folder. When i do so, a handfull errors emerge, mostly concerning 'org.apache' (??)</p>
<p>I just can't figure it out ... so a few hints would be most helpfull.</p>
<p>In advance, thank you :)</p> | 4,825,803 | 17 | 2 | null | 2011-01-24 13:29:23.863 UTC | 116 | 2020-04-16 20:46:55.943 UTC | 2016-08-10 22:19:19.693 UTC | null | 1,269,037 | null | 587,566 | null | 1 | 147 | android|barcode|barcode-scanner|zxing | 160,586 | <h2><strong>UPDATE! - SOLVED + GUIDE</strong></h2>
<p>I've managed to figure it out :) And down below you can read step-by-step guide so it hopefully can help others with the same problem as I had ;)</p>
<ol>
<li>Install Apache Ant - (<a href="http://www.youtube.com/watch?v=XJmndRfb1TU" rel="noreferrer">See this YouTube video for config help</a>)</li>
<li>Download the ZXing source from ZXing homepage and extract it</li>
<li>With the use of Windows Commandline (Run->CMD) navigate to the root directory of the downloaded <code>zxing src</code>.</li>
<li>In the commandline window - Type <code>ant -f core/build.xml</code> press enter and let Apache work it's magic [<em><a href="https://stackoverflow.com/questions/4782543/integration-zxing-library-directly-into-my-android-application/6230861#6230861">having issues?</a></em>]</li>
<li>Enter Eclipse -> new Android Project, based on the android folder in the directory you just extracted</li>
<li>Right-click project folder -> Properties -> Java Build Path -> Library -> Add External JARs...</li>
<li>Navigate to the newly extracted folder and open the core directory and select <code>core.jar</code> ... hit enter!</li>
</ol>
<p>Now you just have to correct a few errors in the translations and the AndroidManifest.xml file :) Now you can happily compile, and you will now have a working standalone barcode scanner app, based on the ZXing source ;)</p>
<p>Happy coding guys - I hope it can help others :)</p> |
4,602,141 | Variable name as a string in Javascript | <p>Is there a way to get a variable name as a string in Javascript? (like <a href="https://developer.apple.com/documentation/foundation/1395257-nsstringfromselector" rel="noreferrer"><code>NSStringFromSelector</code></a> in <a href="https://en.wikipedia.org/wiki/Cocoa_(API)" rel="noreferrer">Cocoa</a>)</p>
<p>I would like to do like this:</p>
<pre><code>var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
</code></pre>
<hr>
<p><strong>UPDATE</strong></p>
<p>I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:</p>
<pre><code>FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
</code></pre>
<p>From another program:</p>
<pre><code>evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
</code></pre>
<p>In PHP:
<a href="https://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php/255335#255335">How to get a variable name as a string in PHP?</a></p> | 4,602,165 | 20 | 4 | null | 2011-01-05 08:40:03.47 UTC | 54 | 2022-06-12 15:32:08.623 UTC | 2019-05-22 05:26:13.2 UTC | user8554766 | null | null | 47,986 | null | 1 | 228 | javascript | 268,115 | <p>Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);</code></pre>
</div>
</div>
</p> |
14,417,318 | CUDA new delete | <p>Can someone give a clear explanation of how the new and delete keywords would behave if called from <code>__device__</code> or <code>__global__</code> code in CUDA 4.2? </p>
<p>Where does the memory get allocated, if its on the device is it local or global? </p>
<p>It terms of context of the problem I am trying to create neural networks on the GPU, I want a linked representation (Like a linked list, but each neuron stores a linked list of connections that hold weights, and pointers to the other neurons), I know I could allocate using <code>cudaMalloc</code> before the kernel launch but I want the kernel to control how and when the networks are created.</p>
<p>Thanks! </p> | 14,417,436 | 1 | 0 | null | 2013-01-19 18:17:41.2 UTC | 13 | 2015-03-30 22:51:50.777 UTC | null | null | null | null | 1,987,797 | null | 1 | 18 | cuda|dynamic-memory-allocation | 11,098 | <p>C++ <code>new</code> and <code>delete</code> operate on device heap memory. The device allows for a portion of the global (i.e. on-board) memory to be allocated in this fashion. <code>new</code> and <code>delete</code> work in a similar fashion to <a href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#dynamic-global-memory-allocation-and-operations" rel="noreferrer">device <code>malloc</code> and <code>free</code></a>.</p>
<p>You can adjust the amount of device global memory available for the heap using a <a href="http://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__DEVICE.html#group__CUDART__DEVICE_1g05956f16eaa47ef3a4efee84563ccb7d" rel="noreferrer">runtime API call</a>. </p>
<p>You may also be interested in the <a href="http://docs.nvidia.com/cuda/cuda-samples/index.html#newdelete" rel="noreferrer">C++ new/delete sample code.</a></p>
<p>CC 2.0 or greater is required for these capabilities.</p> |
14,582,471 | Go memory consumption management | <p>I am new to Go and trying to figure out how it manages memory consumption.</p>
<p>I have trouble with memory in one of my test projects. I don't understand why Go uses more and more memory (never freeing it) when my program runs for a long time.</p>
<p>I am running the test case provided below. After the first allocation, program uses nearly 350 MB of memory (according to ActivityMonitor). Then I try to free it and ActivityMonitor shows that memory consumption doubles. Why?</p>
<p>I am running this code on OS X using Go 1.0.3.</p>
<p>What is wrong with this code? And what is the right way to manage large variables in Go programs?</p>
<p>I had another memory-management-related problem when implementing an algorithm that uses a lot of time and memory; after running it for some time it throws an "out of memory" exception.</p>
<pre><code>package main
import ("fmt"
"time"
)
func main() {
fmt.Println("getting memory")
tmp := make([]uint32, 100000000)
for kk, _ := range tmp {
tmp[kk] = 0
}
time.Sleep(5 * time.Second)
fmt.Println("returning memory")
tmp = make([]uint32, 1)
tmp = nil
time.Sleep(5 * time.Second)
fmt.Println("getting memory")
tmp = make([]uint32, 100000000)
for kk, _ := range tmp {
tmp[kk] = 0
}
time.Sleep(5 * time.Second)
fmt.Println("returning memory")
tmp = make([]uint32, 1)
tmp = nil
time.Sleep(5 * time.Second)
return
}
</code></pre> | 14,586,361 | 2 | 2 | null | 2013-01-29 12:05:04.1 UTC | 8 | 2017-11-29 09:20:08.233 UTC | 2015-06-28 02:10:31.827 UTC | null | 3,614,835 | null | 111,023 | null | 1 | 25 | memory-management|go|memory-consumption | 22,729 | <p>Currently, go uses a <a href="http://en.wikipedia.org/wiki/Mark-and-sweep#Na.C3.AFve_mark-and-sweep" rel="nofollow noreferrer">mark-and-sweep garbage collector</a>, which in general does not define when the object is thrown away.</p>
<p>However, if you look closely, there is a go routine called <a href="https://github.com/golang/go/blob/be589f8d2b721aa86fd5e406733f61a5ed245d3a/src/runtime/proc.go#L4185" rel="nofollow noreferrer"><code>sysmon</code></a> which essentially runs as long as your program does and calls the GC periodically:</p>
<pre><code>// forcegcperiod is the maximum time in nanoseconds between garbage
// collections. If we go this long without a garbage collection, one
// is forced to run.
//
// This is a variable for testing purposes. It normally doesn't change.
var forcegcperiod int64 = 2 * 60 * 1e9
(...)
// If a heap span goes unused for 5 minutes after a garbage collection,
// we hand it back to the operating system.
scavengelimit := int64(5 * 60 * 1e9)
</code></pre>
<p><a href="https://github.com/golang/go/blob/be589f8d2b721aa86fd5e406733f61a5ed245d3a/src/runtime/proc.go#L4175-L4180" rel="nofollow noreferrer"><code>forcegcperiod</code></a> determines the period after which the GC is called by force. <a href="https://github.com/golang/go/blob/be589f8d2b721aa86fd5e406733f61a5ed245d3a/src/runtime/proc.go#L4191-L4193" rel="nofollow noreferrer"><code>scavengelimit</code></a> determines when spans are returned to the operating system. <a href="https://github.com/golang/go/blob/be589f8d2b721aa86fd5e406733f61a5ed245d3a/src/runtime/malloc.go#L22" rel="nofollow noreferrer">Spans are a number of memory pages</a> which can hold several objects. They're kept for <code>scavengelimit</code> time and are freed if no object is on them and <code>scavengelimit</code> is exceeded.</p>
<p>Further down in the code you can see that there is a trace option. You can use this to see, whenever the
scavenger thinks he needs to clean up:</p>
<pre><code>$ GOGCTRACE=1 go run gc.go
gc1(1): 0+0+0 ms 0 -> 0 MB 423 -> 350 (424-74) objects 0 handoff
gc2(1): 0+0+0 ms 1 -> 0 MB 2664 -> 1437 (2880-1443) objects 0 handoff
gc3(1): 0+0+0 ms 1 -> 0 MB 4117 -> 2213 (5712-3499) objects 0 handoff
gc4(1): 0+0+0 ms 2 -> 1 MB 3128 -> 2257 (6761-4504) objects 0 handoff
gc5(1): 0+0+0 ms 2 -> 0 MB 8892 -> 2531 (13734-11203) objects 0 handoff
gc6(1): 0+0+0 ms 1 -> 1 MB 8715 -> 2689 (20173-17484) objects 0 handoff
gc7(1): 0+0+0 ms 2 -> 1 MB 5231 -> 2406 (22878-20472) objects 0 handoff
gc1(1): 0+0+0 ms 0 -> 0 MB 172 -> 137 (173-36) objects 0 handoff
getting memory
gc2(1): 0+0+0 ms 381 -> 381 MB 203 -> 202 (248-46) objects 0 handoff
returning memory
getting memory
returning memory
</code></pre>
<p>As you can see, no gc invoke is done between getting and returning. However, if you change
the delay from 5 seconds to 3 minutes (more than the 2 minutes from <code>forcegcperiod</code>),
the objects are removed by the gc:</p>
<pre><code>returning memory
scvg0: inuse: 1, idle: 1, sys: 3, released: 0, consumed: 3 (MB)
scvg0: inuse: 381, idle: 0, sys: 382, released: 0, consumed: 382 (MB)
scvg1: inuse: 1, idle: 1, sys: 3, released: 0, consumed: 3 (MB)
scvg1: inuse: 381, idle: 0, sys: 382, released: 0, consumed: 382 (MB)
gc9(1): 1+0+0 ms 1 -> 1 MB 4485 -> 2562 (26531-23969) objects 0 handoff
gc10(1): 1+0+0 ms 1 -> 1 MB 2563 -> 2561 (26532-23971) objects 0 handoff
scvg2: GC forced // forcegc (2 minutes) exceeded
scvg2: inuse: 1, idle: 1, sys: 3, released: 0, consumed: 3 (MB)
gc3(1): 0+0+0 ms 381 -> 381 MB 206 -> 206 (252-46) objects 0 handoff
scvg2: GC forced
scvg2: inuse: 381, idle: 0, sys: 382, released: 0, consumed: 382 (MB)
getting memory
</code></pre>
<p>The memory is still not freed, but the GC marked the memory region as unused. Freeing will begin when
the used span is unused and older than <code>limit</code>. From scavenger code:</p>
<pre><code>if(s->unusedsince != 0 && (now - s->unusedsince) > limit) {
// ...
runtime·SysUnused((void*)(s->start << PageShift), s->npages << PageShift);
}
</code></pre>
<p>This behavior may of course change over time, but I hope you now get a bit of a feel when objects
are thrown away by force and when not. </p>
<p>As pointed out by zupa, releasing objects may not return the memory to the operating system, so on
certain systems you may not see a change in memory usage. This seems to be the case for Plan 9
and Windows according to <a href="https://groups.google.com/forum/#!topic/golang-nuts/vfmd6zaRQVs" rel="nofollow noreferrer">this thread on golang-nuts</a>.</p> |
14,886,048 | Options to retrieve the current (on a moment of running query) sequence value | <p>How is it possible to get the current sequence value in postgresql 8.4?</p>
<p>Note: I need the value for the some sort of statistics, just retrieve and store. Nothing related to the concurrency and race conditions in case of manually incrementing it isn't relevant to the question.</p>
<p>Note 2: The sequence is shared across several tables</p>
<p>Note 3: <code>currval</code> won't work because of:</p>
<ul>
<li>Return the value most recently obtained by nextval for this sequence in the current session</li>
<li><code>ERROR: currval of sequence "<sequence name>" is not yet defined in this session</code></li>
</ul>
<p>My current idea: is to parse DDL, which is weird</p> | 14,886,371 | 3 | 5 | null | 2013-02-14 23:39:13.237 UTC | 12 | 2022-09-08 01:23:43.593 UTC | 2013-02-15 00:09:56.127 UTC | null | 251,311 | null | 251,311 | null | 1 | 74 | postgresql|postgresql-8.4 | 67,402 | <p>You may use:</p>
<pre><code>SELECT last_value FROM sequence_name;
</code></pre>
<p><strong>Update</strong>:
this is documented in the <a href="http://www.postgresql.org/docs/current/static/sql-createsequence.html" rel="noreferrer">CREATE SEQUENCE</a> statement:</p>
<blockquote>
<p>Although you cannot update a sequence directly, you can use a query
like:</p>
<p>SELECT * FROM name; </p>
<p>to examine the parameters and current state of a
sequence. In particular, the <strong>last_value</strong> field of the sequence shows
the last value allocated by any session. (Of course, this value might
be obsolete by the time it's printed, if other sessions are actively
doing nextval calls.)</p>
</blockquote> |
62,561,211 | Spring ResponseStatusException does not return reason | <p>I have a very simple <code>@RestController</code>, and I'm trying to set a custom error message. But for some reason, the <code>message</code> for the error is not showing up.</p>
<p>This is my controller:</p>
<pre><code>@RestController
@RequestMapping("openPharmacy")
public class OpenPharmacyController {
@PostMapping
public String findNumberOfSurgeries(@RequestBody String skuLockRequest) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "This postcode is not valid");
}
}
</code></pre>
<p>This is the response that I get:</p>
<pre><code>{
"timestamp": "2020-06-24T17:44:20.194+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/openPharmacy/"
}
</code></pre>
<p>I'm passing a JSON, but I'm not validating anything, I'm just trying to set the custom message. If I change the status code, I see that on the response, but the <code>message</code> is always empty.</p>
<p>Why is this not working like expected? This is such a simple example that I can't see what may be missing. When I debug the code I can see that the error message has all the fields set. But for some reason, the message is never set on the response.</p> | 62,860,392 | 5 | 6 | null | 2020-06-24 17:55:53.133 UTC | 10 | 2022-03-07 06:19:18.347 UTC | null | null | null | null | 10,424,341 | null | 1 | 77 | java|spring-boot|rest|error-handling | 32,131 | <p>This answer was provided by user Hassan in the comments on the original question. I'm only posting it as an answer to give it better visibility.</p>
<p>Basically, all you need to do is add <code>server.error.include-message=always</code> to your application.properties file, and now your message field should be populated.</p>
<p>This behavior was changed in Spring Boot 2.3 which you can read about here: <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content" rel="noreferrer">https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content</a></p> |
2,975,089 | HTML5 Gaussian blur effect | <p>How is apple able to achieve the (apparent) Gaussian blur effect for the photos in the background in this demo:</p>
<p><a href="https://web.archive.org/web/20140420060736/http://www.apple.com/html5/showcase/gallery" rel="nofollow noreferrer">http://www.apple.com/html5/showcase/gallery/</a></p> | 2,975,112 | 3 | 1 | null | 2010-06-04 14:35:57.357 UTC | 2 | 2015-05-01 02:32:21.613 UTC | 2015-05-01 02:32:21.613 UTC | null | 177,525 | null | 41,613 | null | 1 | 9 | webkit | 48,229 | <p>Looking at the source, those are prerendered. No HTML5 trickery for that part, unfortunately.</p>
<p>Example: <a href="http://images.apple.com/html5/showcase/gallery/images/polo9b-small.png" rel="noreferrer">http://images.apple.com/html5/showcase/gallery/images/polo9b-small.png</a></p> |
42,946,335 | Deprecated header <codecvt> replacement | <p>A bit of foreground: my task required converting UTF-8 XML file to UTF-16 (with proper header, of course). And so I searched about usual ways of converting UTF-8 to UTF-16, and found out that one should use templates from <code><codecvt></code>.</p>
<p>But now when it is <a href="https://twitter.com/StephanTLavavej/status/837822661094846465" rel="noreferrer">deprecated</a>, I wonder what is the new common way of doing the same task?</p>
<p>(Don't mind using Boost at all, but other than that I prefer to stay as close to standard library as possible.)</p> | 42,946,556 | 4 | 0 | null | 2017-03-22 08:32:29.773 UTC | 16 | 2021-10-01 18:07:14.853 UTC | 2017-11-27 09:45:44.723 UTC | null | 7,561,577 | null | 7,561,577 | null | 1 | 90 | c++|utf-8|c++17|utf-16|codecvt | 27,878 | <p><code>std::codecvt</code> template from <code><locale></code> itself isn't deprecated. For UTF-8 to UTF-16, there is still <code>std::codecvt<char16_t, char, std::mbstate_t></code> specialization.</p>
<p>However, since <code>std::wstring_convert</code> and <code>std::wbuffer_convert</code> are deprecated along with the standard conversion facets, there isn't any easy way to convert strings using the facets.</p>
<p>So, as Bolas already answered: Implement it yourself (or you can use a third party library, as always) or keep using the deprecated API.</p> |
38,509,538 | Numpy: Checking if a value is NaT | <pre><code>nat = np.datetime64('NaT')
nat == nat
>> FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
np.isnan(nat)
>> TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code></pre>
<p>How can I check if a datetime64 is NaT? I can't seem to dig anything out of the docs. I know Pandas can do it, but I'd rather not add a dependency for something so basic.</p> | 38,531,233 | 6 | 5 | null | 2016-07-21 16:25:01.36 UTC | 16 | 2018-12-14 09:20:48.967 UTC | null | null | null | null | 3,813,324 | null | 1 | 73 | python|numpy | 169,628 | <p><strong>INTRO:</strong> This answer was written in a time when Numpy was version 1.11 and behaviour of NAT comparison was supposed to change since version 1.12. Clearly that wasn't the case and the second part of answer became wrong. The first part of answer may be not applicable for new versions of numpy. Be sure you've checked MSeifert's answers below.
<hr>
When you make a comparison at the first time, you always have a warning. But meanwhile returned result of comparison is correct:</p>
<pre><code>import numpy as np
nat = np.datetime64('NaT')
def nat_check(nat):
return nat == np.datetime64('NaT')
nat_check(nat)
Out[4]: FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
True
nat_check(nat)
Out[5]: True
</code></pre>
<p>If you want to suppress the warning you can use the <a href="https://docs.python.org/3.5/library/warnings.html#temporarily-suppressing-warnings" rel="noreferrer">catch_warnings</a> context manager:</p>
<pre><code>import numpy as np
import warnings
nat = np.datetime64('NaT')
def nat_check(nat):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')
nat_check(nat)
Out[5]: True
</code></pre>
<p><hr/>
<strong>EDIT:</strong> For some reason behavior of NAT comparison in Numpy version 1.12 wasn't change, so the next code turned out to be inconsistent.</p>
<p><s>And finally you might check numpy version to handle changed behavior since version 1.12.0:</p>
<pre><code>def nat_check(nat):
if [int(x) for x in np.__version__.split('.')[:-1]] > [1, 11]:
return nat != nat
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')
</code></pre>
<p></s><hr/>
<strong>EDIT:</strong> As <a href="https://stackoverflow.com/a/43836217/5510499">MSeifert</a> mentioned, Numpy contains <code>isnat</code> function since version 1.13.</p> |
22,899,946 | LDAP vs SAML Authorization | <p>I'm currently investigating moving an asset tracking system from LDAP to SAML. There are two main areas where our software currently uses LDAP. The first is authentication. In order to access the system today you need to successfully authenticate with LDAP and be a member of a specified LDAP group. That part is fairly simple to move over to SAML. We've utilized a library to handle most of the dirty work. And on the IDP we can add a claim to authorize the user. But our second use of LDAP is throwing me for a loop.</p>
<p>Today, each asset that we maintain has the ability to be linked to a username. For example, a particular printer may belong to 'someuser'. One of the options our software gives the administrator is to view/interact with assets based on LDAP user groups. So as an administrator, I may want to update all the printers that are owned by people in a particular department. To accomplish this, the administrator would create a rule scoped to the LDAP group 'departmentInQuestion'. Our software would then use a service account to connect to LDAP, create a query to see which users from our system are in 'departmentInQuestion', execute that and use the results to determine which assets should get the update.</p>
<p>So far from my searching I have not been able to find a SAML workflow analogous to this. It appears the only opportunity we have to asses 'someuser' is when they authenticate and we get access to their claims. But in our workflow 'someuser' may never authenticate with us. It's almost as if we're using authorizing a user on behalf of the service account. Is there an existing workflow that I've overlooked during my exploration? Are there any other technologies that support authorization in this manner? </p>
<p>Thanks for any input! </p> | 22,902,276 | 2 | 0 | null | 2014-04-06 20:58:08.683 UTC | 11 | 2018-08-18 03:56:28.053 UTC | null | null | null | null | 256,828 | null | 1 | 20 | authentication|ldap|authorization|saml | 60,375 | <p>SAML is like a passport or a visa. It has (trusted) information about you that can be used to know about you (e.g. your name, DOB) and infer what you can access (e.g. entrance to a country). You can use properties in the token to query other systems about additional information you might be associated with (e.g. your bank statement).</p>
<p>So, analogously, SAML is typically used to authenticate users to a system (once you trust it's origin), but there're no provisions for managing user profiles, or 'resources'.</p>
<p>Authorization decisions, if any, are often made based on the attributes associated with the user (e.g. the group he belongs to) and conveyed in claims in the security token.</p>
<p>Perhaps the 1st questions to answer is why you want to move away from LDAP and thinking about SAML. Is it because you want to accept users logging in with their own credentials? Is it because you want to get rid of the LDAP server altogether</p>
<p>You could perfectly well keep your LDAP server for managing <code>resources associated with users</code>, and authenticate users somewhere else. This is what you have now. You would correlate users "outside" and "inside" via a common attribute (e.g. a username, or some ID).</p>
<p>If you want to get rid of LDAP all together, then you'd need someplace else to store that information (e.g. your app database).</p> |
2,918,016 | Delphi 7: ADO, need basic coding example | <p>I am a complete beginner here. Can someone please post some Delphi code to </p>
<ul>
<li>create a database</li>
<li>add a simple table</li>
<li>close the database</li>
</ul>
<p>then, later</p>
<ul>
<li>open a database</li>
<li>read each table</li>
<li>read each field of a given table</li>
<li>perform a simple search</li>
</ul>
<p>Sorry to be so clueless. I did google, but didn't find a useful tutorial ...</p>
<p>In addition, it would be useful if the underlying database were MySql (5.1.36) (I don't even know if that makes any difference)</p> | 2,918,812 | 3 | 0 | null | 2010-05-27 01:56:46.193 UTC | 8 | 2012-05-02 20:54:10.277 UTC | 2012-05-02 20:54:10.277 UTC | null | 850,152 | null | 192,910 | null | 1 | 11 | delphi|ado | 51,765 | <p>@mawg, i wrote an simple program for you to ilustrate how work with ADO and Delphi. this is an console application, but explains the basics.</p>
<p>before you execute this code you must download and install the odbc connector from this <a href="http://dev.mysql.com/downloads/connector/odbc/3.51.html" rel="noreferrer">location</a>.</p>
<p>You can improve and adapt this code to your requirements.</p>
<pre><code>program ProjectMysqlADO;
{$APPTYPE CONSOLE}
uses
ActiveX,
DB,
ADODB,
SysUtils;
const
//the connection string
StrConnection='Driver={MySQL ODBC 3.51 Driver};Server=%s;Database=%s;User=%s; Password=%s;Option=3;';
var
AdoConnection : TADOConnection;
procedure SetupConnection(DataBase:String);//Open a connection
begin
Writeln('Connecting to MySQL');
AdoConnection:=TADOConnection.Create(nil);
AdoConnection.LoginPrompt:=False;//dont ask for the login parameters
AdoConnection.ConnectionString:=Format(StrConnection,['your_server',DataBase,'your_user','your_password']);
AdoConnection.Connected:=True; //open the connection
Writeln('Connected');
end;
procedure CloseConnection;//Close an open connection
begin
Writeln('Closing connection to MySQL');
if AdoConnection.Connected then
AdoConnection.Close;
AdoConnection.Free;
Writeln('Connection closed');
end;
procedure CreateDatabase(Database:string);
begin
Writeln('Creating Database '+database);
AdoConnection.Execute('CREATE DATABASE IF NOT EXISTS '+Database,cmdText);
Writeln('Database '+database+' created');
end;
procedure CreateTables;
begin
Writeln('Creating Tables');
AdoConnection.Execute(
'CREATE TABLE IF NOT EXISTS customers ('+
'id INT,'+
'name VARCHAR(100),'+
'country VARCHAR(25) )',cmdText);
Writeln('Tables Created');
end;
procedure DeleteData;
begin
Writeln('Deleting dummy data');
AdoConnection.Execute('DELETE FROM customers');
Writeln('Data deleted');
end;
procedure InsertData;
Procedure InsertReg(id:integer;name,country:string);
var
ADOCommand : TADOCommand;
begin
ADOCommand:=TADOCommand.Create(nil);
try
ADOCommand.Connection:=AdoConnection;
ADOCommand.Parameters.Clear;
ADOCommand.CommandText:='INSERT INTO customers (id,name,country) VALUES (:id,:name,:country)';
ADOCommand.ParamCheck:=False;
ADOCommand.Parameters.ParamByName('id').Value := id;
ADOCommand.Parameters.ParamByName('name').Value := name;
ADOCommand.Parameters.ParamByName('country').Value := country;
ADOCommand.Execute;
finally
ADOCommand.Free;
end;
end;
begin
Writeln('Inserting Data');
InsertReg(1,'Lilian Kelly','UK');
InsertReg(2,'John and Sons','USA');
InsertReg(3,'William Suo','USA');
InsertReg(4,'MARCOTEC','UK');
Writeln('Data Inserted');
end;
procedure ReadData;
var
AdoQuery : TADOQuery;
begin
AdoQuery:=TADOQuery.Create(nil);
try
AdoQuery.Connection:=AdoConnection;
AdoQuery.SQL.Add('SELECT * FROM customers');
AdoQuery.Open;
while not AdoQuery.eof do
begin
Writeln(format('%s %s %s',[AdoQuery.FieldByname('id').AsString,AdoQuery.FieldByname('name').AsString,AdoQuery.FieldByname('country').AsString]));
AdoQuery.Next;
end;
finally
AdoQuery.Free;
end;
end;
begin
CoInitialize(nil); // call CoInitialize()
try
Writeln('Init');
try
SetupConnection('mysql'); //first will connect to the mysql database , this database always exist
CreateDatabase('Mydb'); //now we create the database
CloseConnection; //close the original connection
SetupConnection('Mydb'); //open the connection pointing to the Mydb database
CreateTables; //create a sample table
DeleteData; //Delete the dummy data before insert
InsertData; //insert a dummy data
ReadData; //read the inserted data
CloseConnection; //close the connection
except
on E : Exception do
Writeln(E.Classname, ': ', E.Message);
end;
Readln;
finally
CoUnInitialize; // free memory
end;
end.
</code></pre> |
3,185,664 | How to delete Eclipse completely (including settings and plugins) from Mac OS X? | <p>My Eclipse with GAE broken and works strangely.
So I deleted Eclipse from Application folder, but there is garbage left. I re-downloaded fresh new eclipse, but it runs with old settings, and broken GAE structure remained.</p>
<p>How can I DELETE completely Eclipse from my Mac? (without any kind of settings/plugins/logs etc.)</p> | 3,185,723 | 3 | 1 | null | 2010-07-06 11:08:51.91 UTC | 6 | 2015-07-08 21:30:32.19 UTC | 2015-07-08 21:30:32.19 UTC | null | 4,370,109 | null | 246,776 | null | 1 | 27 | eclipse|macos|uninstallation | 47,106 | <p>Eclipse itself will be installed where you've unzipped the file you've downloaded. This directory contains <code>Eclipse.app</code>, <code>configuration/</code>, <code>plugins/</code> and <code>features/</code> (amongst others).</p>
<p>Your <code>workspace/</code> directory (in your home directory by default) contains all your projects and various settings too, in <code>workspace/.metadata/</code> (see dot files if you want to have a look). Deleting the workspace will delete your own project files of course, so you would need to make sure you have a way to restore them from a clean version (for example from a version control system if you're using one).</p>
<p>If you don't want to delete your entire workspace, it might be worth moving it away and then copying the projects back in, leaving the new <code>workspace/.metadata/</code> clean, to see if this fixes your problem.</p> |
2,558,257 | How can you display upside down text with a textview in Android? | <p>How can you display upside down text with a textview in Android?</p>
<p>In my case I have a 2 player game, where they play across from each other. I want to display test to the second player oriented to them.</p>
<hr>
<p>This was the solution I implemented after AaronMs advice</p>
<p>The class that does the overriding, bab.foo.UpsideDownText </p>
<pre><code>package bab.foo;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.TextView;
public class UpsideDownText extends TextView {
//The below two constructors appear to be required
public UpsideDownText(Context context) {
super(context);
}
public UpsideDownText(Context context, AttributeSet attrs)
{
super(context, attrs);
}
@Override
public void onDraw(Canvas canvas) {
//This saves off the matrix that the canvas applies to draws, so it can be restored later.
canvas.save();
//now we change the matrix
//We need to rotate around the center of our text
//Otherwise it rotates around the origin, and that's bad.
float py = this.getHeight()/2.0f;
float px = this.getWidth()/2.0f;
canvas.rotate(180, px, py);
//draw the text with the matrix applied.
super.onDraw(canvas);
//restore the old matrix.
canvas.restore();
}
}
</code></pre>
<p>And this is my XML layout:</p>
<pre><code><bab.foo.UpsideDownText
android:text="Score: 0"
android:id="@+id/tvScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
>
</bab.foo.UpsideDownText>
</code></pre> | 17,765,543 | 3 | 0 | null | 2010-04-01 05:14:03.317 UTC | 7 | 2013-07-20 19:06:24.767 UTC | 2010-04-02 04:37:59.473 UTC | null | 92,212 | null | 92,212 | null | 1 | 29 | android|textview | 24,491 | <p>in the xml file add: </p>
<pre><code>android:rotation = "180"
</code></pre>
<p>in the respective element to display text upside down.</p>
<p>for example:</p>
<pre><code><TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="TextView"
android:rotation="180"/>
</code></pre> |
2,777,422 | In SQL Azure how can I create a read only user | <p>I would like to create an SQL Azure user and grant her read-only access on a handful of DBs, what script can I use to achieve this? </p> | 2,777,553 | 3 | 1 | null | 2010-05-05 23:19:53.493 UTC | 21 | 2018-05-03 20:08:09.957 UTC | 2018-05-03 20:08:09.957 UTC | null | 1,145,114 | null | 17,174 | null | 1 | 40 | sql|sql-server|tsql|azure-sql-database | 37,500 | <p>A pure TSQL script is super messy, SQL Azure disables the <code>USE</code> command, so you are stuck opening connections to each DB you need to give the user read access. </p>
<p>This is the gist of the pattern. </p>
<p>In Master DB:</p>
<pre><code>CREATE LOGIN reader WITH password='YourPWD';
-- grant public master access
CREATE USER readerUser FROM LOGIN reader;
</code></pre>
<p>In each target DB (requires a separate connection)</p>
<pre><code>CREATE USER readerUser FROM LOGIN reader;
EXEC sp_addrolemember 'db_datareader', 'readerUser';
</code></pre> |
38,511,373 | Change the color of text within a pandas dataframe html table python using styles and css | <p>I have a pandas dataframe:</p>
<pre><code>arrays = [['Midland', 'Midland', 'Hereford', 'Hereford', 'Hobbs','Hobbs', 'Childress',
'Childress', 'Reese', 'Reese', 'San Angelo', 'San Angelo'],
['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(np.random.randn(12, 4), index=arrays,
columns=['00 UTC', '06 UTC', '12 UTC', '18 UTC'])
</code></pre>
<p>The table that prints <code>df</code> from this looks like this:<a href="https://i.stack.imgur.com/FbsI6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FbsI6.png" alt="enter image description here"></a></p>
<p>I would like to color all of the values in the 'MOS' rows a certain color and color the left two index/header columns as well as the top header row a different background color than the rest of the cells with values in them. Any ideas how I can do this?</p> | 38,511,805 | 2 | 0 | null | 2016-07-21 18:06:19.587 UTC | 9 | 2021-03-09 06:33:28.377 UTC | 2017-09-11 18:13:15.197 UTC | null | 2,137,255 | null | 5,586,573 | null | 1 | 12 | python|html|css|pandas|dataframe | 29,297 | <p>This takes a few steps:</p>
<p>First import <code>HTML</code> and <code>re</code></p>
<pre><code>from IPython.display import HTML
import re
</code></pre>
<p>You can get at the <code>html</code> pandas puts out via the <code>to_html</code> method.</p>
<pre><code>df_html = df.to_html()
</code></pre>
<p>Next we are going to generate a random identifier for the html table and style we are going to create.</p>
<pre><code>random_id = 'id%d' % np.random.choice(np.arange(1000000))
</code></pre>
<p>Because we are going to insert some style, we need to be careful to specify that this style will only be for our table. Now let's insert this into the <code>df_html</code></p>
<pre><code>df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)
</code></pre>
<p>And create a style tag. This is really up to you. I just added some hover effect.</p>
<pre><code>style = """
<style>
table#{random_id} tr:hover {{background-color: #f5f5f5}}
</style>
""".format(random_id=random_id)
</code></pre>
<p>Finally, display it</p>
<pre><code>HTML(style + df_html)
</code></pre>
<h3>Function all in one.</h3>
<pre><code>def HTML_with_style(df, style=None, random_id=None):
from IPython.display import HTML
import numpy as np
import re
df_html = df.to_html()
if random_id is None:
random_id = 'id%d' % np.random.choice(np.arange(1000000))
if style is None:
style = """
<style>
table#{random_id} {{color: blue}}
</style>
""".format(random_id=random_id)
else:
new_style = []
s = re.sub(r'</?style>', '', style).strip()
for line in s.split('\n'):
line = line.strip()
if not re.match(r'^table', line):
line = re.sub(r'^', 'table ', line)
new_style.append(line)
new_style = ['<style>'] + new_style + ['</style>']
style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))
df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)
return HTML(style + df_html)
</code></pre>
<p>Use it like this:</p>
<pre><code>HTML_with_style(df.head())
</code></pre>
<p><a href="https://i.stack.imgur.com/iSiyr.png"><img src="https://i.stack.imgur.com/iSiyr.png" alt="enter image description here"></a></p>
<pre><code>HTML_with_style(df.head(), '<style>table {color: red}</style>')
</code></pre>
<p><a href="https://i.stack.imgur.com/LfFrq.png"><img src="https://i.stack.imgur.com/LfFrq.png" alt="enter image description here"></a></p>
<pre><code>style = """
<style>
tr:nth-child(even) {color: green;}
tr:nth-child(odd) {color: aqua;}
</style>
"""
HTML_with_style(df.head(), style)
</code></pre>
<p><a href="https://i.stack.imgur.com/a95aW.png"><img src="https://i.stack.imgur.com/a95aW.png" alt="enter image description here"></a></p>
<p>Learn CSS and go nuts!</p> |
35,928,534 | 403 "Request had insufficient authentication scopes" during gcloud container cluster get-credentials | <p>From a VM in GCE, I did the following</p>
<pre><code>gcloud auth activate-service-account --key-file <blah>
# "blah" is a service account key file (JSON) I generated from the web interface
gcloud config set project <project-name>
gcloud config set compute/zone <zone-name>
gcloud set container/cluster <cluster-name>
</code></pre>
<p>Then when I tried to run </p>
<pre><code>gcloud container clusters get-credentials <cluster-name>
</code></pre>
<p>and it failed with the error message:</p>
<blockquote>
<p>Error message: "ERROR: (gcloud.container.clusters.get-credentials)
ResponseError: code=403, message=Request had insufficient
authentication scopes."</p>
</blockquote>
<p>The VM is on the same network as the GKE cluster. I tried the same thing, with the same service account key file from a machine outside GCE, against a GKE cluster on the "default" network and it succeeded...</p> | 35,932,921 | 4 | 0 | null | 2016-03-10 22:22:39.9 UTC | 7 | 2020-11-16 16:49:15.933 UTC | 2018-05-17 21:52:13.98 UTC | null | 322,020 | null | 2,116,766 | null | 1 | 38 | google-cloud-platform|google-kubernetes-engine | 48,388 | <p>To use the Google Kubernetes Engine API from a GCE virtual machine you need to add the cloud platform scope ("<a href="https://www.googleapis.com/auth/cloud-platform" rel="noreferrer">https://www.googleapis.com/auth/cloud-platform</a>") to your VM when it is created. </p> |
44,876,778 | How can I use a local file on container? | <p>I'm trying create a container to run a program. I'm using a pre configurate image and now I need run the program. However, it's a machine learning program and I need a dataset from my computer to run. </p>
<p>The file is too large to be copied to the container. It would be best if the program running in the container searched the dataset in a local directory of my computer, but I don't know how I can do this.</p>
<p>Is there any way to do this reference with some docker command? Or using Dockerfile?</p> | 44,876,899 | 1 | 0 | null | 2017-07-03 01:54:26.7 UTC | 26 | 2019-07-12 16:20:48.707 UTC | 2017-07-03 02:31:49.83 UTC | null | 515,189 | null | 8,245,887 | null | 1 | 120 | docker|dockerfile|boot2docker|docker-machine | 125,769 | <p>Yes, you can do this. What you are describing is a bind mount. See <a href="https://docs.docker.com/storage/bind-mounts/" rel="noreferrer">https://docs.docker.com/storage/bind-mounts/</a> for documentation on the subject.</p>
<p>For example, if I want to mount a folder from my home directory into <code>/mnt/mydata</code> in a container, I can do:</p>
<pre><code>docker run -v /Users/andy/mydata:/mnt/mydata myimage
</code></pre>
<p>Now, <code>/mnt/mydata</code> inside the container will have access to <code>/Users/andy/mydata</code> on my host.</p>
<p>Keep in mind, if you are using Docker for Mac or Docker for Windows there are specific directories on the host that are allowed by default:</p>
<blockquote>
<p>If you are using Docker Machine on Mac or Windows, your Docker Engine daemon has only limited access to your macOS or Windows filesystem. Docker Machine tries to auto-share your /Users (macOS) or C:\Users (Windows) directory. So, you can mount files or directories on macOS using.</p>
</blockquote>
<p><strong>Update July 2019:</strong></p>
<p>I've updated the documentation link and naming to be correct. These type of mounts are called "bind mounts". The snippet about Docker for Mac or Windows no longer appears in the documentation but it should still apply. I'm not sure why they removed it (my Docker for Mac still has an explicit list of allowed mounting paths on the host).</p> |
44,663,903 | Pandas: split column of lists of unequal length into multiple columns | <p>I have a Pandas dataframe that looks like the below:</p>
<pre><code> codes
1 [71020]
2 [77085]
3 [36415]
4 [99213, 99287]
5 [99233, 99233, 99233]
</code></pre>
<p>I'm trying to split the lists in <code>df['codes']</code> into columns, like the below:</p>
<pre><code> code_1 code_2 code_3
1 71020
2 77085
3 36415
4 99213 99287
5 99233 99233 99233
</code></pre>
<p>where columns that don't have a value (because the list was not that long) are filled with blanks or NaNs or something.</p>
<p>I've seen answers like <a href="https://stackoverflow.com/questions/35491274/pandas-split-column-of-lists-into-multiple-columns">this one</a> and others similar to it, and while they work on lists of equal length, they all throw errors when I try to use the methods on lists of unequal length. Is there a good way do to this?</p> | 44,663,989 | 3 | 0 | null | 2017-06-20 22:18:56.197 UTC | 16 | 2022-03-08 10:17:07.873 UTC | null | null | null | null | 2,446,029 | null | 1 | 23 | python|pandas | 15,628 | <p>Try:</p>
<pre><code>pd.DataFrame(df.codes.values.tolist()).add_prefix('code_')
code_0 code_1 code_2
0 71020 NaN NaN
1 77085 NaN NaN
2 36415 NaN NaN
3 99213 99287.0 NaN
4 99233 99233.0 99233.0
</code></pre>
<hr>
<p>Include the <code>index</code></p>
<pre><code>pd.DataFrame(df.codes.values.tolist(), df.index).add_prefix('code_')
code_0 code_1 code_2
1 71020 NaN NaN
2 77085 NaN NaN
3 36415 NaN NaN
4 99213 99287.0 NaN
5 99233 99233.0 99233.0
</code></pre>
<hr>
<p>We can nail down all the formatting with this:</p>
<pre><code>f = lambda x: 'code_{}'.format(x + 1)
pd.DataFrame(
df.codes.values.tolist(),
df.index, dtype=object
).fillna('').rename(columns=f)
code_1 code_2 code_3
1 71020
2 77085
3 36415
4 99213 99287
5 99233 99233 99233
</code></pre> |
65,806,330 | toomanyrequests: You have reached your pull rate limit. You may increase the limit by authenticating and upgrading | <p>Why does this happen, when I want to build an image from a Dockerfile in CodeCommit with CodeBuild?</p>
<p>I get this Error:</p>
<blockquote>
<p>toomanyrequests: You have reached your pull rate limit. You may increase the limit by authenticating and upgrading: <a href="https://www.docker.com/increase-rate-limit" rel="noreferrer">https://www.docker.com/increase-rate-limit</a></p>
</blockquote> | 65,806,626 | 8 | 0 | null | 2021-01-20 09:08:18.727 UTC | 8 | 2022-08-27 16:43:48.393 UTC | 2022-08-27 16:42:50.027 UTC | null | 10,962,477 | null | 12,581,323 | null | 1 | 46 | python|amazon-web-services|docker|dockerfile|aws-codebuild | 52,482 | <p>Try not to pull the images from the docker hub because docker has throttling for pulling the images.</p>
<p>Use <a href="https://aws.amazon.com/ecr/" rel="noreferrer">ECR(Elastic Container Registry)</a> for private images and <a href="https://gallery.ecr.aws/" rel="noreferrer">Amazon ECR Public Gallery</a> for public docker images.
<a href="https://aws.amazon.com/blogs/containers/advice-for-customers-dealing-with-docker-hub-rate-limits-and-a-coming-soon-announcement/" rel="noreferrer">Advice for customers dealing with Docker Hub rate limits, and a Coming Soon announcement</a> for the advice from AWS for handling this.</p> |
22,753,328 | C++ error -- expression must have integral or enum type -- getting this from a string with concatenation? | <p>C++ error <strong>expression must have integral or enum type</strong> getting this from a string with concatenation?</p>
<p>So in the <code>toString()</code> of a class in C++ I have the code:</p>
<pre><code>string bags = "Check in " + getBags() + " bags";
</code></pre>
<p>I thought I could declare a string like this? (I'm coming from a Java background and trying to learn C++). The <code>bags</code> is underlined in Visual Studio though and the problem is:</p>
<blockquote>
<p>expression must have integral or enum type.</p>
</blockquote>
<p><code>getBags()</code> just returns an <code>int</code>. </p>
<p>Another example where this happens is with:</p>
<pre><code>string totalPrice = "Grand Total: " + getTotalPrice();
</code></pre>
<p><code>getTotalPrice()</code> returns a <code>float</code> and is what is underlined with the error. </p>
<p>But then if I put in a line like:</p>
<pre><code>string blah = getBags() + "blah";
</code></pre>
<p>No errors.</p>
<p>What am I not understanding here?</p> | 22,753,422 | 3 | 0 | null | 2014-03-31 03:49:09.277 UTC | 1 | 2017-03-14 09:16:39.78 UTC | 2017-03-14 09:16:39.78 UTC | null | 1,017,853 | null | 3,448,228 | null | 1 | 25 | c++ | 40,508 | <p><code>"Check in "</code> is actually a <code>const char *</code>.
Adding <code>getBags()</code> (an <code>int</code>) to it yields another <code>const char*</code>. The compiler error is generated because you cannot add two pointers.</p>
<p>You need to convert both <code>"Check in "</code> and <code>getBags()</code> to strings before concatenating them:</p>
<pre><code>string bags = std::string("Check in ") + std::to_string(getBags()) + " bags";
</code></pre>
<p><code>" bags"</code> will be implicitly converted to a <code>string</code>.</p> |
40,522,256 | How to print converted SQL query from yii2 query | <p>I want to print query:</p>
<pre><code>$demo = Demo::find()->all();
</code></pre>
<p>I want to see converted SQL query with parameters:</p>
<pre><code>createCommand()->getRawSql();
</code></pre>
<p>is showing me an error message: </p>
<blockquote>
<p>yii2 Call to a member function createCommand() on a non-object</p>
</blockquote>
<p>Please help me to see the actual SQL query.</p> | 40,549,741 | 6 | 2 | null | 2016-11-10 07:40:17.73 UTC | 2 | 2021-06-15 10:57:02.55 UTC | 2016-11-12 15:22:08.77 UTC | null | 1,351,076 | null | 6,755,292 | null | 1 | 17 | yii2 | 48,128 | <p>Eg:</p>
<pre><code>$query = Demo::find()->where(['category'=>2]);
echo $query->createCommand()->getRawSql();
</code></pre> |
40,438,851 | Use Javascript to check if JSON object contain value | <p>I want to check if a certain key in a JSON object like the one below contains a certain value. Let's say I want to check if the key "name", in any of the objects, has the value "Blofeld" (which is true). How can I do that?</p>
<pre><code>[ {
"id" : 19,
"cost" : 400,
"name" : "Arkansas",
"height" : 198,
"weight" : 35
}, {
"id" : 21,
"cost" : 250,
"name" : "Blofeld",
"height" : 216,
"weight" : 54
}, {
"id" : 38,
"cost" : 450,
"name" : "Gollum",
"height" : 147,
"weight" : 22
} ]
</code></pre> | 40,439,116 | 4 | 3 | null | 2016-11-05 13:34:57.69 UTC | 14 | 2021-09-29 11:03:44.207 UTC | 2019-02-02 10:57:22.797 UTC | null | 6,439,240 | null | 1,711,950 | null | 1 | 33 | javascript|json|object|key | 120,893 | <p>you can also use <code>Array.some()</code> function:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [
{
id: 19,
cost: 400,
name: 'Arkansas',
height: 198,
weight: 35
},
{
id: 21,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
},
{
id: 38,
cost: 450,
name: 'Gollum',
height: 147,
weight: 22
}
];
console.log(arr.some(item => item.name === 'Blofeld'));
console.log(arr.some(item => item.name === 'Blofeld2'));
// search for object using lodash
const objToFind1 = {
id: 21,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
};
const objToFind2 = {
id: 211,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
};
console.log(arr.some(item => _.isEqual(item, objToFind1)));
console.log(arr.some(item => _.isEqual(item, objToFind2)));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script></code></pre>
</div>
</div>
</p> |
2,717,757 | How do I rename an R object? | <p>I'm using the quantmod package to import financial series data from Yahoo.</p>
<pre><code>library(quantmod)
getSymbols("^GSPC")
[1] "GSPC"
</code></pre>
<p>I'd like to change the name of object "GSPC" to "SPX". I've tried the rename function in the reshape package, but it only changes the variable names. The "GSPC" object has vectors GSPC.Open, GSPC.High, etc. I'd like my renaming of "GSPC" to "SPX" to also change GSPC.Open to SPX.Open and so on.</p> | 2,717,853 | 1 | 0 | null | 2010-04-26 23:46:11.243 UTC | 13 | 2020-07-03 05:53:54.42 UTC | 2019-09-06 10:57:12.017 UTC | null | 680,068 | null | 296,155 | null | 1 | 27 | r|rename|quantmod | 51,309 | <p>Renaming an object and the colnames within it is a two step process:</p>
<pre><code>SPY <- GSPC # assign the object to the new name (creates a copy)
colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY)) # rename the column names
</code></pre>
<p>Otherwise, the getSymbols function allows you to <em>not</em> auto assign, in which case you could skip the first step (you will still need to rename the columns).</p>
<pre><code>SPY <- getSymbols("^GSPC", auto.assign=FALSE)
</code></pre>
<hr>
<p><em>Comment from @backlin</em></p>
<p>R employs so-called <em>lazy evaluation</em>. An effect of that is that when you "copy" <code>SPY <- GSPC</code> you do not actually allocate new space in the memory for <code>SPY</code>. R knows the objects are identical and only makes a new copy in the memory if one of them is modified (<em>i.e.</em> when they are no longer the identical, <em>e.g.</em> when you change the column names on the following line). So by doing</p>
<pre><code>SPY <- GSPC
rm(GSPC)
colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY))
</code></pre>
<p>you never really copy <code>GSPC</code> but merely give it a new name (<code>SPY</code>) and then tell R to forget the first name (<code>GSPC</code>). When you then change the column names you do not need to create a new copy of <code>SPY</code> since <code>GSPC</code> no longer exists, meaning you have truly renamed the object without creating intermediate copies.</p> |
34,320,046 | IFrame height issues on iOS (mobile safari) | <p>Example page source:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Page</title>
</head>
<body>
<div class="main" style="height: 100%;">
<div class="header" style="height: 100px; background-color: green;"></div>
<iframe src="http://www.wikipedia.com"
style="height: 200px; width: 100%; border: none;"></iframe>
<div class="footer" style="height: 100px; background-color: green;"></div>
</div>
</body>
</html>
</code></pre>
<p>The problem is, that <code>height</code> of <code>200px</code> from the IFrames inline style is ignored on mobile safari:</p>
<p><a href="https://i.stack.imgur.com/prSh3.png"><img src="https://i.stack.imgur.com/prSh3.png" alt="enter image description here"></a></p>
<p>Also I'd like to change the height of the IFrame dynamically via vanilla JavaScript which is not working at all with the following code:</p>
<pre><code>document.getElementsByTagName('iframe')[0].style.height = "100px"
</code></pre>
<p>The value of the <code>height</code> style is changed correctly according to the dev tools but it's simply ignored since the actually rendered height of the IFrame doesn't change.</p>
<p>This only seems to be a problem in mobile Safari and is working as expected on the latest versions of desktop Safari, Firefox, Chrome, Androids WebView etc.</p>
<p>Testpage: <a href="http://devpublic.blob.core.windows.net/scriptstest/index.html">http://devpublic.blob.core.windows.net/scriptstest/index.html</a></p>
<p><em>Ps.:</em> I tested this with various devices on browserstack and also took the screenshots there since I don't have no actual iDevice at hand.</p> | 34,320,508 | 3 | 0 | null | 2015-12-16 19:02:39.973 UTC | 8 | 2018-10-10 20:17:01.553 UTC | 2015-12-16 19:08:28.51 UTC | null | 1,273,551 | null | 1,273,551 | null | 1 | 24 | javascript|ios|iphone|iframe|mobile-safari | 44,047 | <p>It looks like this: <a href="https://stackoverflow.com/questions/23083462/how-to-get-an-iframe-to-be-responsive-in-ios-safari">How to get an IFrame to be responsive in iOS Safari?</a> </p>
<p>iFrames have an issue on iOS only, so you have to adapt your iframe to it. </p>
<p>You can put a div wrapping the iframe, set css on the iframe and, what worked for me, was to add: put the attribute scrolling='no'. </p>
<p>Wishing you luck. </p> |
21,218,577 | Transparent color of Bootstrap-3 Navbar | <p>I'm having problem with setting bootstrap3 navbar transparency or opacity color. I didin't change anything in bootstrap.css or bootstrap-theme.css
In my menu I'm Trying to put image under that and set color to black-transparent or black with opacity like here:
<a href="https://i.imgur.com/f9NNwtD.png" rel="noreferrer">http://i.imgur.com/f9NNwtD.png</a>
You can see that opacity ammount is not very high but it is , and i have to do something like that. When I'm changing anything the color is setting white so please help me.</p>
<p>The Code below: </p>
<pre><code><div class="navbar transparent navbar-inverse navbar-static-top hr">
<div class="navbar-brand logo"></div>
<div class="navbar-brand-right">
</div>
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav mineul" style="font-size:17px;margin-top:9px; color:white;">
<li><a href="#">Test1</a></li>
<li><a href="#">Test1</a></li>
<li><a href="#">Test1</a></li>
</ul>
</div>
</div>
</div>
</code></pre>
<p>And bootply:
<a href="http://bootply.com/106966" rel="noreferrer">http://bootply.com/106966</a></p> | 21,218,643 | 4 | 0 | null | 2014-01-19 15:19:29.373 UTC | 12 | 2017-12-05 14:08:19.917 UTC | null | null | null | null | 1,964,443 | null | 1 | 14 | html|css|twitter-bootstrap | 119,587 | <pre class="lang-css prettyprint-override"><code>.navbar {
background-color: transparent;
background: transparent;
border-color: transparent;
}
.navbar li { color: #000 }
</code></pre>
<p><a href="http://bootply.com/106969" rel="noreferrer">http://bootply.com/106969</a></p> |
24,917,194 | Spring Boot - inject map from application.yml | <p>I have a <a href="http://projects.spring.io/spring-boot/" rel="noreferrer">Spring Boot</a> application with the following <code>application.yml</code> - taken basically from <a href="http://docs.spring.io/spring-boot/docs/1.1.4.RELEASE/reference/htmlsingle/#production-ready-application-info" rel="noreferrer">here</a>:</p>
<pre><code>info:
build:
artifact: ${project.artifactId}
name: ${project.name}
description: ${project.description}
version: ${project.version}
</code></pre>
<p>I can inject particular values, e.g.</p>
<pre><code>@Value("${info.build.artifact}") String value
</code></pre>
<p>I would like, however, to inject the whole map, i.e. something like this:</p>
<pre><code>@Value("${info}") Map<String, Object> info
</code></pre>
<p>Is that (or something similar) possible? Obviously, I can load yaml directly, but was wondering if there's something already supported by Spring.</p> | 24,921,330 | 8 | 0 | null | 2014-07-23 17:35:38.433 UTC | 29 | 2021-01-17 16:05:43.443 UTC | null | null | null | null | 3,821,009 | null | 1 | 118 | java|spring|spring-boot | 194,413 | <p>You can have a map injected using <code>@ConfigurationProperties</code>:</p>
<pre><code>import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
public class MapBindingSample {
public static void main(String[] args) throws Exception {
System.out.println(SpringApplication.run(MapBindingSample.class, args)
.getBean(Test.class).getInfo());
}
@Bean
@ConfigurationProperties
public Test test() {
return new Test();
}
public static class Test {
private Map<String, Object> info = new HashMap<String, Object>();
public Map<String, Object> getInfo() {
return this.info;
}
}
}
</code></pre>
<p>Running this with the yaml in the question produces:</p>
<pre><code>{build={artifact=${project.artifactId}, version=${project.version}, name=${project.name}, description=${project.description}}}
</code></pre>
<p>There are various options for setting a prefix, controlling how missing properties are handled, etc. See the <a href="http://docs.spring.io/spring-boot/docs/1.1.4.RELEASE/api/org/springframework/boot/context/properties/ConfigurationProperties.html" rel="noreferrer">javadoc</a> for more information.</p> |
37,737,538 | Merge matplotlib subplots with shared x-axis | <p>I have two graphs to where both have the same x-axis, but with different y-axis scalings. </p>
<p>The plot with regular axes is the data with a trend line depicting a decay while the y semi-log scaling depicts the accuracy of the fit.</p>
<pre><code>fig1 = plt.figure(figsize=(15,6))
ax1 = fig1.add_subplot(111)
# Plot of the decay model
ax1.plot(FreqTime1,DecayCount1, '.', color='mediumaquamarine')
# Plot of the optimized fit
ax1.plot(x1, y1M, '-k', label='Fitting Function: $f(t) = %.3f e^{%.3f\t} \
%+.3f$' % (aR1,kR1,bR1))
ax1.set_xlabel('Time (sec)')
ax1.set_ylabel('Count')
ax1.set_title('Run 1 of Cesium-137 Decay')
# Allows me to change scales
# ax1.set_yscale('log')
ax1.legend(bbox_to_anchor=(1.0, 1.0), prop={'size':15}, fancybox=True, shadow=True)
</code></pre>
<p><a href="https://i.stack.imgur.com/qzJwy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qzJwy.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/ci4jI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ci4jI.png" alt="enter image description here"></a></p>
<p>Now, i'm trying to figure out to implement both close together like the examples supplied by this link
<a href="http://matplotlib.org/examples/pylab_examples/subplots_demo.html" rel="noreferrer">http://matplotlib.org/examples/pylab_examples/subplots_demo.html</a></p>
<p>In particular, this one</p>
<p><a href="https://i.stack.imgur.com/1DNBU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1DNBU.png" alt="enter image description here"></a></p>
<p>When looking at the code for the example, i'm a bit confused on how to implant 3 things:</p>
<p>1) Scaling the axes differently</p>
<p>2) Keeping the figure size the same for the exponential decay graph but having a the line graph have a smaller y size and same x size.</p>
<p>For example:</p>
<p><a href="https://i.stack.imgur.com/o32et.png" rel="noreferrer"><img src="https://i.stack.imgur.com/o32et.png" alt="enter image description here"></a></p>
<p>3) Keeping the label of the function to appear in just only the decay graph.</p>
<p>Any help would be most appreciated.</p> | 37,738,851 | 3 | 0 | null | 2016-06-09 23:01:41.717 UTC | 13 | 2021-11-19 01:04:35.967 UTC | 2017-10-16 10:58:37.063 UTC | null | 2,666,859 | null | 5,597,830 | null | 1 | 28 | python|matplotlib|subplot | 76,091 | <p>Look at the code and comments in it:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from matplotlib import gridspec
# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
fig = plt.figure()
# set height ratios for subplots
gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])
# the first subplot
ax0 = plt.subplot(gs[0])
# log scale for axis Y of the first subplot
ax0.set_yscale("log")
line0, = ax0.plot(x, y, color='r')
# the second subplot
# shared axis X
ax1 = plt.subplot(gs[1], sharex = ax0)
line1, = ax1.plot(x, y, color='b', linestyle='--')
plt.setp(ax0.get_xticklabels(), visible=False)
# remove last tick label for the second subplot
yticks = ax1.yaxis.get_major_ticks()
yticks[-1].label1.set_visible(False)
# put legend on first subplot
ax0.legend((line0, line1), ('red line', 'blue line'), loc='lower left')
# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/09ynX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/09ynX.png" alt="enter image description here" /></a></p> |
37,806,625 | sqlalchemy: create relations but without foreign key constraint in db? | <p>Since <code>sqlalchemy.orm.relationship()</code> already implies the relation, and I do not want to create a constraint in db. What should I do?</p>
<p>Currently I manually remove these constraints after alembic migrations.</p> | 37,809,175 | 1 | 0 | null | 2016-06-14 08:20:08.433 UTC | 11 | 2018-01-05 13:04:09.46 UTC | 2018-01-05 13:04:09.46 UTC | null | 2,681,632 | null | 41,948 | null | 1 | 35 | python|orm|sqlalchemy|foreign-keys | 19,786 | <p>Instead of defining "schema" level <a href="http://docs.sqlalchemy.org/en/latest/core/constraints.html#sqlalchemy.schema.ForeignKey" rel="noreferrer"><code>ForeignKey</code></a> constraints create a <a href="http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#creating-custom-foreign-conditions" rel="noreferrer">custom foreign condition</a>; pass what columns you'd like to use as "foreign keys" and the <a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship.params.primaryjoin" rel="noreferrer"><code>primaryjoin</code></a> to <a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship" rel="noreferrer"><code>relationship</code></a>. You have to manually define the <a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship.params.primaryjoin" rel="noreferrer"><code>primaryjoin</code></a> because:</p>
<blockquote>
<p>By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table).</p>
</blockquote>
<pre><code>In [2]: class A(Base):
...: a_id = Column(Integer, primary_key=True)
...: __tablename__ = 'a'
...:
In [3]: class C(Base):
...: c_id = Column(Integer, primary_key=True)
...: a_id = Column(Integer)
...: __tablename__ = 'c'
...: a = relationship('A', foreign_keys=[a_id],
...: primaryjoin='A.a_id == C.a_id')
...:
</code></pre>
<p>Foreign keys can also be annotated inline in the <a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship.params.primaryjoin" rel="noreferrer"><code>primaryjoin</code></a> using <a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.foreign" rel="noreferrer"><code>foreign()</code></a>:</p>
<pre><code>a = relationship('A', primaryjoin='foreign(C.a_id) == A.a_id')
</code></pre>
<p>You can verify that no <code>FOREIGN KEY</code> constraints are emitted for table <em>c</em>:</p>
<pre><code>In [4]: from sqlalchemy.schema import CreateTable
In [5]: print(CreateTable(A.__table__))
CREATE TABLE a (
a_id INTEGER NOT NULL,
PRIMARY KEY (a_id)
)
In [6]: print(CreateTable(C.__table__))
CREATE TABLE c (
c_id INTEGER NOT NULL,
a_id INTEGER,
PRIMARY KEY (c_id)
)
</code></pre>
<p><strong>Warning:</strong></p>
<p>Note that without a <code>FOREIGN KEY</code> constraint in place on the DB side you can blow your referential integrity to pieces any which way you want. There's a relationship at the ORM/application level, but it cannot be enforced in the DB.</p> |
49,174,673 | aws s3api create-bucket —bucket make exception | <p>I am trying to create an S3 bucket using </p>
<p><code>aws s3api create-bucket —bucket kubernetes-aws-wthamira-io</code></p>
<p>It gives this error: </p>
<pre class="lang-sh prettyprint-override"><code>An error occurred (IllegalLocationConstraintException) when calling
the CreateBucket operation: The unspecified location constraint is
incompatible for the region specific endpoint this request was sent
to.
</code></pre>
<p>I set the region using <code>aws configure</code> to <code>eu-west-1</code> </p>
<pre><code>Default region name [eu-west-1]:
</code></pre>
<p>but it gives the same error. How do I solve this?</p>
<p>I use osx terminal to connect aws </p> | 49,174,798 | 9 | 1 | null | 2018-03-08 13:47:06.043 UTC | 6 | 2022-09-24 11:32:58.067 UTC | 2019-10-16 08:05:15.71 UTC | null | 539,481 | null | 5,446,671 | null | 1 | 38 | amazon-web-services|amazon-s3|kubernetes|kops | 24,877 | <p>try this:</p>
<pre><code>aws s3api create-bucket --bucket kubernetes-aws-wthamira-io --create-bucket-configuration LocationConstraint=eu-west-1
</code></pre>
<p>Regions outside of <code>us-east-1</code> require the appropriate <code>LocationConstraint</code> to be specified in order to create the bucket in the desired region.</p>
<p><a href="https://docs.aws.amazon.com/cli/latest/reference/s3api/create-bucket.html" rel="noreferrer">https://docs.aws.amazon.com/cli/latest/reference/s3api/create-bucket.html</a></p> |
38,425,871 | Should Kotlin files be put in a separate source directory in Android? | <p>I'm going to start using Kotlin for Android development in addition to Java because of its benefits. I have installed the Android Studio plugin and included the relevant dependencies in my gradle files.</p>
<p>So I've read from the Kotlin documentation and Stack Overflow that it's possible to include a separate source directory for Kotlin files, like so:</p>
<blockquote>
<p>app:<br>
-manifest<br>
-java<br>
<strong>-kotlin</strong><br>
-res </p>
</blockquote>
<p>I know I can create this directory by adding the following to my <code>build.gradle</code> file:</p>
<pre><code>sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
</code></pre>
<p>My question is: <strong>should Kotlin files 'live' with Java files in the same directory or not?</strong></p>
<p>In addition to opinions, I would like to know whether there is a particular convention for this, and if so, why it is the way that it is.</p>
<p>If not, then what are the advantages and disadvantages of each option?</p> | 38,432,455 | 2 | 0 | null | 2016-07-17 20:58:32.573 UTC | 3 | 2017-05-13 12:22:54.463 UTC | 2017-05-13 12:22:54.463 UTC | null | 4,230,345 | null | 4,230,345 | null | 1 | 31 | java|android|kotlin | 5,877 | <p>Putting the Kotlin files in a separate source directory exists as a documented possibility because in early (pre-1.0) versions of Kotlin this was the only supported setup. Afterwards, the Kotlin Gradle plugin was made more flexible, so the directory separation is no longer necessary. I'm not aware of any benefits that could be gained by putting Kotlin files in a separate source directory.</p>
<p>Having a separate source directory is especially inconvenient when you have a Java project which you're gradually converting to Kotlin. Moving each converted file to a different source directory makes the conversion process unnecessarily more cumbersome.</p> |
1,008,783 | Using varargs from Scala | <p>I'm tearing my hair out trying to figure out how to do the following:</p>
<pre><code>def foo(msf: String, o: Any, os: Any*) = {
println( String.format(msf, o :: List(os:_*)) )
}
</code></pre>
<p>There's a reason why I have to declare the method with an <code>o</code> and an <code>os</code> <code>Seq</code> separately. Basically, I end up with the format method called with a single object parameter (of type <code>List </code>). Attempting:</p>
<pre><code>def foo(msf: String, o: Any, os: Any*) = {
println( String.format(msf, (o :: List(os:_*))).toArray )
}
</code></pre>
<p>Gives me the type error:</p>
<blockquote>
<p>found: Array[Any]</p>
<p>required Seq[java.lang.Object]</p>
</blockquote>
<p>I've tried casting, which compiles but fails for pretty much the same reason as the first example. When I try</p>
<pre><code>println(String.format(msg, (o :: List(os:_*)) :_* ))
</code></pre>
<p>this fails to compile with implicit conversion ambiguity (<code>any2ArrowAssoc</code> and <code>any2stringadd</code>)</p> | 1,008,836 | 2 | 0 | null | 2009-06-17 18:28:18.443 UTC | 12 | 2009-06-21 15:45:06.743 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 16,853 | null | 1 | 55 | scala|variadic-functions | 47,378 | <pre><code>def foo(msf: String, o: AnyRef, os: AnyRef*) =
println( String.format(msf, (o :: os.toList).toArray : _* ))
</code></pre> |
2,336,435 | PowerShell: How to limit string to N characters? | <p>substring complains when I try to limit a string to 10 characters which is not 10 or more characters in length. I know I can test the length but I would like to know if there is a single cmdlet which will do what I need.</p>
<pre><code>PS C:\> "12345".substring(0,5)
12345
PS C:\> "12345".substring(0,10)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At line:1 char:18
+ "12345".substring( <<<< 0,10)
</code></pre> | 2,336,499 | 5 | 0 | null | 2010-02-25 18:07:38.957 UTC | 1 | 2018-12-07 09:57:34.127 UTC | null | null | null | null | 4,527 | null | 1 | 18 | powershell | 62,149 | <p>Do you need exactly a cmdlet? I wonder why you don't like getting length. If it's part of a script, then it looks fine.</p>
<pre><code>$s = "12345"
$s.substring(0, [System.Math]::Min(10, $s.Length))
</code></pre> |
3,134,020 | Error when running library(ggplot2) | <p>I just updated to R 2.11.1 and after installing ggplot2, I tried </p>
<pre><code>library(ggplot2)
</code></pre>
<p>and got </p>
<pre><code>Loading required package: proto
Loading required package: grid Loading
required package: reshape Loading
required package: plyr Loading
required package: digest Error in
eval(expr, envir, enclos) : could not
find function "proto" In addition:
Warning message: In library(package,
lib.loc = lib.loc, character.only =
TRUE, logical.return = TRUE, :
there is no package called 'proto'
Error : unable to load R code in
package 'ggplot2' Error:
package/namespace load failed for
'ggplot2'
</code></pre>
<p>Any help appreciated.</p> | 3,135,467 | 5 | 4 | null | 2010-06-28 16:03:23.3 UTC | 10 | 2021-06-09 14:29:52.51 UTC | 2014-03-09 15:30:06.767 UTC | null | 1,270,695 | null | 228,220 | null | 1 | 35 | r|ggplot2 | 54,984 | <p><code>install.packages('ggplot2', dep = TRUE)</code> would do the trick... install <code>proto</code> package</p> |
2,940,367 | What is more efficient? Using pow to square or just multiply it with itself? | <p>What of these two methods is in C more efficient? And how about:</p>
<pre><code>pow(x,3)
</code></pre>
<p>vs. </p>
<pre><code>x*x*x // etc?
</code></pre> | 2,940,800 | 7 | 8 | null | 2010-05-30 21:17:52.673 UTC | 31 | 2021-06-05 01:21:54.543 UTC | 2013-05-01 13:15:02.74 UTC | null | 1,219,006 | user163408 | null | null | 1 | 149 | c++|c|optimization | 131,275 | <p><strong>UPDATE 2021</strong></p>
<p>I've modified the benchmark code as follows:</p>
<ul>
<li>std::chrono used for timing measurements instead of boost</li>
<li>C++11 <code><random></code> used instead of <code>rand()</code></li>
<li>Avoid repeated operations that can get hoisted out. The base parameter is ever-changing.</li>
</ul>
<p>I get the following results with GCC 10 -O2 (in seconds):</p>
<pre><code>exp c++ pow c pow x*x*x...
2 0.204243 1.39962 0.0902527
3 1.36162 1.38291 0.107679
4 1.37717 1.38197 0.106103
5 1.3815 1.39139 0.117097
</code></pre>
<p>GCC 10 -O3 is almost identical to GCC 10 -O2.</p>
<p>With GCC 10 -O2 -ffast-math:</p>
<pre><code>exp c++ pow c pow x*x*x...
2 0.203625 1.4056 0.0913414
3 0.11094 1.39938 0.108027
4 0.201593 1.38618 0.101585
5 0.102141 1.38212 0.10662
</code></pre>
<p>With GCC 10 -O3 -ffast-math:</p>
<pre><code>exp c++ pow c pow x*x*x...
2 0.0451995 1.175 0.0450497
3 0.0470842 1.20226 0.051399
4 0.0475239 1.18033 0.0473844
5 0.0522424 1.16817 0.0522291
</code></pre>
<p>With Clang 12 -O2:</p>
<pre><code>exp c++ pow c pow x*x*x...
2 0.106242 0.105435 0.105533
3 1.45909 1.4425 0.102235
4 1.45629 1.44262 0.108861
5 1.45837 1.44483 0.1116
</code></pre>
<p>Clang 12 -O3 is almost identical to Clang 12 -O2.</p>
<p>With Clang 12 -O2 -ffast-math:</p>
<pre><code>exp c++ pow c pow x*x*x...
2 0.0233731 0.0232457 0.0231076
3 0.0271074 0.0266663 0.0278415
4 0.026897 0.0270698 0.0268115
5 0.0312481 0.0296402 0.029811
</code></pre>
<p>Clang 12 -O3 -ffast-math is almost identical to Clang 12 -O2 -ffast-math.</p>
<p>Machine is Intel Core i7-7700K on Linux 5.4.0-73-generic x86_64.</p>
<p>Conclusions:</p>
<ul>
<li>With GCC 10 (no -ffast-math), <code>x*x*x...</code> is <em>always</em> faster</li>
<li>With GCC 10 -O2 -ffast-math, <code>std::pow</code> is as fast as <code>x*x*x...</code> for <em>odd</em> exponents</li>
<li>With GCC 10 -O3 -ffast-math, <code>std::pow</code> is as fast as <code>x*x*x...</code> for all test cases, and is around twice as fast as -O2.</li>
<li>With GCC 10, C's <code>pow(double, double)</code> is always much slower</li>
<li>With Clang 12 (no -ffast-math), <code>x*x*x...</code> is faster for exponents greater than 2</li>
<li>With Clang 12 -ffast-math, all methods produce similar results</li>
<li>With Clang 12, <code>pow(double, double)</code> is as fast as <code>std::pow</code> for integral exponents</li>
<li>Writing benchmarks without having the compiler outsmart you is <strong>hard</strong>.</li>
</ul>
<p>I'll eventually get around to installing a more recent version of GCC on my machine and will update my results when I do so.</p>
<p>Here's the updated benchmark code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cmath>
#include <chrono>
#include <iostream>
#include <random>
using Moment = std::chrono::high_resolution_clock::time_point;
using FloatSecs = std::chrono::duration<double>;
inline Moment now()
{
return std::chrono::high_resolution_clock::now();
}
#define TEST(num, expression) \
double test##num(double b, long loops) \
{ \
double x = 0.0; \
\
auto startTime = now(); \
for (long i=0; i<loops; ++i) \
{ \
x += expression; \
b += 1.0; \
} \
auto elapsed = now() - startTime; \
auto seconds = std::chrono::duration_cast<FloatSecs>(elapsed); \
std::cout << seconds.count() << "\t"; \
return x; \
}
TEST(2, b*b)
TEST(3, b*b*b)
TEST(4, b*b*b*b)
TEST(5, b*b*b*b*b)
template <int exponent>
double testCppPow(double base, long loops)
{
double x = 0.0;
auto startTime = now();
for (long i=0; i<loops; ++i)
{
x += std::pow(base, exponent);
base += 1.0;
}
auto elapsed = now() - startTime;
auto seconds = std::chrono::duration_cast<FloatSecs>(elapsed); \
std::cout << seconds.count() << "\t"; \
return x;
}
double testCPow(double base, double exponent, long loops)
{
double x = 0.0;
auto startTime = now();
for (long i=0; i<loops; ++i)
{
x += ::pow(base, exponent);
base += 1.0;
}
auto elapsed = now() - startTime;
auto seconds = std::chrono::duration_cast<FloatSecs>(elapsed); \
std::cout << seconds.count() << "\t"; \
return x;
}
int main()
{
using std::cout;
long loops = 100000000l;
double x = 0;
std::random_device rd;
std::default_random_engine re(rd());
std::uniform_real_distribution<double> dist(1.1, 1.2);
cout << "exp\tc++ pow\tc pow\tx*x*x...";
cout << "\n2\t";
double b = dist(re);
x += testCppPow<2>(b, loops);
x += testCPow(b, 2.0, loops);
x += test2(b, loops);
cout << "\n3\t";
b = dist(re);
x += testCppPow<3>(b, loops);
x += testCPow(b, 3.0, loops);
x += test3(b, loops);
cout << "\n4\t";
b = dist(re);
x += testCppPow<4>(b, loops);
x += testCPow(b, 4.0, loops);
x += test4(b, loops);
cout << "\n5\t";
b = dist(re);
x += testCppPow<5>(b, loops);
x += testCPow(b, 5.0, loops);
x += test5(b, loops);
std::cout << "\n" << x << "\n";
}
</code></pre>
<hr />
<p><strong>Old Answer, 2010</strong></p>
<p>I tested the performance difference between <code>x*x*...</code> vs <code>pow(x,i)</code> for small <code>i</code> using this code:</p>
<pre><code>#include <cstdlib>
#include <cmath>
#include <boost/date_time/posix_time/posix_time.hpp>
inline boost::posix_time::ptime now()
{
return boost::posix_time::microsec_clock::local_time();
}
#define TEST(num, expression) \
double test##num(double b, long loops) \
{ \
double x = 0.0; \
\
boost::posix_time::ptime startTime = now(); \
for (long i=0; i<loops; ++i) \
{ \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
x += expression; \
} \
boost::posix_time::time_duration elapsed = now() - startTime; \
\
std::cout << elapsed << " "; \
\
return x; \
}
TEST(1, b)
TEST(2, b*b)
TEST(3, b*b*b)
TEST(4, b*b*b*b)
TEST(5, b*b*b*b*b)
template <int exponent>
double testpow(double base, long loops)
{
double x = 0.0;
boost::posix_time::ptime startTime = now();
for (long i=0; i<loops; ++i)
{
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
x += std::pow(base, exponent);
}
boost::posix_time::time_duration elapsed = now() - startTime;
std::cout << elapsed << " ";
return x;
}
int main()
{
using std::cout;
long loops = 100000000l;
double x = 0.0;
cout << "1 ";
x += testpow<1>(rand(), loops);
x += test1(rand(), loops);
cout << "\n2 ";
x += testpow<2>(rand(), loops);
x += test2(rand(), loops);
cout << "\n3 ";
x += testpow<3>(rand(), loops);
x += test3(rand(), loops);
cout << "\n4 ";
x += testpow<4>(rand(), loops);
x += test4(rand(), loops);
cout << "\n5 ";
x += testpow<5>(rand(), loops);
x += test5(rand(), loops);
cout << "\n" << x << "\n";
}
</code></pre>
<p>Results are:</p>
<pre><code>1 00:00:01.126008 00:00:01.128338
2 00:00:01.125832 00:00:01.127227
3 00:00:01.125563 00:00:01.126590
4 00:00:01.126289 00:00:01.126086
5 00:00:01.126570 00:00:01.125930
2.45829e+54
</code></pre>
<p>Note that I accumulate the result of every pow calculation to make sure the compiler doesn't optimize it away.</p>
<p>If I use the <code>std::pow(double, double)</code> version, and <code>loops = 1000000l</code>, I get:</p>
<pre><code>1 00:00:00.011339 00:00:00.011262
2 00:00:00.011259 00:00:00.011254
3 00:00:00.975658 00:00:00.011254
4 00:00:00.976427 00:00:00.011254
5 00:00:00.973029 00:00:00.011254
2.45829e+52
</code></pre>
<p>This is on an Intel Core Duo running Ubuntu 9.10 64bit. Compiled using gcc 4.4.1 with -o2 optimization.</p>
<p>So in C, yes <code>x*x*x</code> will be faster than <code>pow(x, 3)</code>, because there is no <code>pow(double, int)</code> overload. In C++, it will be the roughly same. (Assuming the methodology in my testing is correct.)</p>
<hr />
<p>This is in response to the comment made by An Markm:</p>
<p>Even if a <code>using namespace std</code> directive was issued, if the second parameter to <code>pow</code> is an <code>int</code>, then the <code>std::pow(double, int)</code> overload from <code><cmath></code> will be called instead of <code>::pow(double, double)</code> from <code><math.h></code>.</p>
<p>This test code confirms that behavior:</p>
<pre><code>#include <iostream>
namespace foo
{
double bar(double x, int i)
{
std::cout << "foo::bar\n";
return x*i;
}
}
double bar(double x, double y)
{
std::cout << "::bar\n";
return x*y;
}
using namespace foo;
int main()
{
double a = bar(1.2, 3); // Prints "foo::bar"
std::cout << a << "\n";
return 0;
}
</code></pre> |
3,066,356 | Multiple CSS Classes: Properties Overlapping based on the order defined | <p>Is there a rule in CSS that determines the cascading order when multiple classes are defined on an element? (<code>class="one two"</code> vs <code>class="two one"</code>)</p>
<p>Right now, there seems to be no such effect.</p>
<p>Example: both divs are orange in color on Firefox</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
.one { border: 6px dashed green }
.two { border: 6px dashed orange }
</style>
</head>
<body>
<div class="one two">
hello world
</div>
<div class="two one">
hello world
</div>
</code></pre> | 3,066,365 | 8 | 2 | null | 2010-06-17 23:38:19.53 UTC | 14 | 2014-02-01 12:46:43.247 UTC | 2010-06-17 23:47:52.193 UTC | null | 317,975 | null | 325,418 | null | 1 | 72 | web-standards|css | 38,733 | <p>It depends on which one is declared last in your stylesheet. For example,</p>
<pre><code>.one { border: 6px dashed green }
.two { border: 6px dashed orange }
</code></pre>
<p>vs</p>
<pre><code>.two { border: 6px dashed green }
.one { border: 6px dashed orange }
</code></pre> |
2,601,027 | How can I check if a file exists in Perl? | <p>I have a relative path </p>
<pre><code> $base_path = "input/myMock.TGZ";
</code></pre>
<p><code>myMock.TGZ</code> is the file name located in input folder.
The filename can change. But the path is always stored in <code>$base_path</code>.</p>
<p>I need to check if the file exists in <code>$base_path</code>.</p> | 2,601,042 | 8 | 0 | null | 2010-04-08 15:09:09.553 UTC | 15 | 2021-06-15 20:51:26.89 UTC | 2013-07-30 06:58:21.223 UTC | null | 1,009,479 | null | 305,196 | null | 1 | 122 | perl | 298,201 | <p>Test whether <em>something</em> exists at given path using the <code>-e</code> file-test operator.</p>
<pre><code>print "$base_path exists!\n" if -e $base_path;
</code></pre>
<p>However, this test is probably broader than you intend. The code above will generate output if a plain file exists at that path, but it will also fire for a directory, a named pipe, a symlink, or a more exotic possibility. <a href="http://perldoc.perl.org/functions/-X.html" rel="noreferrer">See the documentation</a> for details.</p>
<p>Given the extension of <code>.TGZ</code> in your question, it seems that you expect a <em>plain file</em> rather than the alternatives. The <code>-f</code> file-test operator asks whether a path leads to a plain file.</p>
<pre><code>print "$base_path is a plain file!\n" if -f $base_path;
</code></pre>
<p>The perlfunc documentation covers the long list of <a href="http://perldoc.perl.org/functions/-X.html" rel="noreferrer">Perl's file-test operators</a> that covers many situations you will encounter in practice.</p>
<blockquote>
<ul>
<li><strong><code>-r</code></strong><br>
File is readable by effective uid/gid.</li>
<li><strong><code>-w</code></strong><br>
File is writable by effective uid/gid.</li>
<li><strong><code>-x</code></strong><br>
File is executable by effective uid/gid.</li>
<li><strong><code>-o</code></strong><br>
File is owned by effective uid.</li>
<li><strong><code>-R</code></strong><br>
File is readable by real uid/gid.</li>
<li><strong><code>-W</code></strong><br>
File is writable by real uid/gid.</li>
<li><strong><code>-X</code></strong><br>
File is executable by real uid/gid.</li>
<li><strong><code>-O</code></strong><br>
File is owned by real uid.</li>
<li><strong><code>-e</code></strong><br>
File exists.</li>
<li><strong><code>-z</code></strong><br>
File has zero size (is empty).</li>
<li><strong><code>-s</code></strong><br>
File has nonzero size (returns size in bytes).</li>
<li><strong><code>-f</code></strong><br>
File is a plain file.</li>
<li><strong><code>-d</code></strong><br>
File is a directory.</li>
<li><strong><code>-l</code></strong><br>
File is a symbolic link (false if symlinks aren’t supported by the file system).</li>
<li><strong><code>-p</code></strong><br>
File is a named pipe (FIFO), or Filehandle is a pipe.</li>
<li><strong><code>-S</code></strong><br>
File is a socket.</li>
<li><strong><code>-b</code></strong><br>
File is a block special file.</li>
<li><strong><code>-c</code></strong><br>
File is a character special file.</li>
<li><strong><code>-t</code></strong><br>
Filehandle is opened to a tty.</li>
<li><strong><code>-u</code></strong><br>
File has setuid bit set.</li>
<li><strong><code>-g</code></strong><br>
File has setgid bit set.</li>
<li><strong><code>-k</code></strong><br>
File has sticky bit set.</li>
<li><strong><code>-T</code></strong><br>
File is an ASCII or UTF-8 text file (heuristic guess).</li>
<li><strong><code>-B</code></strong><br>
File is a “binary” file (opposite of <code>-T</code>).</li>
<li><strong><code>-M</code></strong><br>
Script start time minus file modification time, in days.</li>
<li><strong><code>-A</code></strong><br>
Same for access time.</li>
<li><strong><code>-C</code></strong><br>
Same for inode change time (Unix, may differ for other platforms)</li>
</ul>
</blockquote> |
2,862,084 | How do I create sub-applications in Django? | <p>I'm a Django newbie, but fairly experienced at programming. I have a set of related applications that I'd like to group into a sub-application but can not figure out how to get manage.py to do this for me.</p>
<p>Ideally I'll end up with a structure like:</p>
<pre><code>project/
app/
subapp1/
subapp2/
</code></pre>
<p>I've tried <code>manage.py startapp app.subapp1</code> and <code>manage.py startapp app/subapp1</code><br>
but this tells me that <code>/</code> and <code>.</code> are invalid characters for app names.</p>
<p>I've tried changing into the app directory and running <code>../manage.py subapp1</code> but that makes supapp1 at the top level. NOTE, I'm <strong>not</strong> trying to directly make a stand-alone application. I'm trying to do all this from within a project.</p> | 2,863,509 | 9 | 4 | null | 2010-05-19 00:24:35.32 UTC | 14 | 2022-09-07 03:34:05.333 UTC | 2013-06-30 20:35:08.113 UTC | user1040049 | null | null | 340,632 | null | 1 | 68 | django | 42,196 | <p>You can still do this :</p>
<pre><code>cd app
django-admin startapp subapp1
</code></pre>
<p>This will work (create the application basic structure), however <code>app</code> and <code>subapp1</code> will still be considered as two unrelated applications in the sense that you have to add both of them to <code>INSTALLED_APPS</code> in your settings.</p>
<p>Does this answer your question ? Otherwise you should tell more about what you are trying to do.</p> |
2,513,479 | redirect prints to log file | <p>Okay. I have completed my first python program.It has around 1000 lines of code.
During development I placed plenty of <code>print</code> statements before running a command using <code>os.system()</code>
say something like,</p>
<pre><code>print "running command",cmd
os.system(cmd)
</code></pre>
<p>Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remove all <code>print</code> statements - since some provide useful info for user) into a log file will be more useful? Any tricks or tips. </p> | 2,513,511 | 10 | 3 | null | 2010-03-25 06:25:21.423 UTC | 24 | 2022-01-21 19:30:06.76 UTC | 2010-03-25 15:26:43.007 UTC | null | 12,855 | null | 246,365 | null | 1 | 46 | python|logging|printing | 114,332 | <p>Python lets you capture and assign sys.stdout - as mentioned - to do this:</p>
<pre><code>import sys
old_stdout = sys.stdout
log_file = open("message.log","w")
sys.stdout = log_file
print "this will be written to message.log"
sys.stdout = old_stdout
log_file.close()
</code></pre> |
2,587,669 | Can I use a :before or :after pseudo-element on an input field? | <p>I am trying to use the <code>:after</code> CSS pseudo-element on an <code>input</code> field, but it does not work. If I use it with a <code>span</code>, it works OK. </p>
<pre><code><style type="text/css">
.mystyle:after {content:url(smiley.gif);}
.mystyle {color:red;}
</style>
</code></pre>
<p>This works (puts the smiley after "buu!" and before "some more")</p>
<pre><code><span class="mystyle">buuu!</span>a some more
</code></pre>
<p>This does not work - it only colors someValue in red, but there is no smiley.</p>
<pre><code><input class="mystyle" type="text" value="someValue">
</code></pre>
<p>What am I doing wrong? should I use another pseudo-selector?</p>
<p>Note: I cannot add a <code>span</code> around my <code>input</code>, because it is being generated by a third-party control.</p> | 2,591,460 | 22 | 1 | null | 2010-04-06 19:28:08.357 UTC | 115 | 2022-02-15 19:23:31.297 UTC | 2017-11-14 04:16:52.83 UTC | null | 106,224 | null | 174,638 | null | 1 | 804 | html|css|pseudo-element|css-content | 622,293 | <p><code>:after</code> and <code>:before</code> are not supported in Internet Explorer 7 and under, on any elements.</p>
<p>It's also not meant to be used on replaced elements such as <strong>form elements</strong> (inputs) and <strong>image elements</strong>.</p>
<p>In other words it's <strong>impossible</strong> with pure CSS.</p>
<p>However if using <a href="http://jquery.com" rel="noreferrer">jquery</a> you can use</p>
<pre><code>$(".mystyle").after("add your smiley here");
</code></pre>
<p><a href="http://api.jquery.com/after/" rel="noreferrer">API docs on .after</a></p>
<p>To append your content with javascript. This will work across all browsers.</p> |
25,286,967 | How to create an alert message in jsp page after submit process is complete | <p>I am trying to add a message in my jsp after the process is done by hitting the submit button.</p>
<pre><code>function onSubmit() {
alert("Master_Data.xlsx and Consistency_Check_Data.xlsx are located under d:/stage/MasterDataReports");
}
</script>
<body>
<form name="input" action="getMasterData" method="get">
<br />
<br />
<h1 align='center'>Master Data File</h1>
<br />
<br />
<table border="0" align='center'>
<tr>
<td>
<h2>Site Name</h2>
</td>
<td align='left'>
<jsp:useBean id="masterDao" class="master.dao.MasterDataDao"/>
<select name="siteId" id="siteId">
<option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td>
<h2>Division</h2>
</td>
<td align='left'>
<jsp:useBean id="masterDaoUtil" class="master.dao.util.MasterDataConstants"/>
<select name="divisionId" id="divisionId">
<option value="33"><%=MasterDataConstants.DIVISION_TYPE_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="31"><%=MasterDataConstants.DIVISION_TYPE_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="34"><%=MasterDataConstants.DIVISION_TYPE_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="35"><%=MasterDataConstants.DIVISION_TYPE_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="23"><%=MasterDataConstants.DIVISION_TYPE_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
</select></td>
</tr>
</table>
<br />
<br />
<div style="text-align: center">
**strong text**<input type="submit" value="Submit" OnClick="onSubmit()">
</div>
</code></pre>
<p>Right now the submit process will only happen after I clear the alert. Is there a way that I can either pop an alert after the submit process is done or if I can add a message to the jsp page?
Thanks in advance
Sonny</p>
<p>Here is my updated Servlet that is causing error:</p>
<pre><code>package master.service;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
**strong text**import javax.servlet.http.HttpSession;
@SuppressWarnings("serial")
public class MasterDataServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response, HttpSession session)
throws IOException, ServletException {
MasterDataService masterDataService = new MasterDataService();
try {
int siteId = Integer.parseInt(request.getParameter("siteId"));
int divisionId = Integer.parseInt(request.getParameter("divisionId"));
//For master data file
masterDataService.createMasterDataFile(siteId, divisionId,false);
//For consistency checker file
masterDataService.createMasterDataFile(siteId, divisionId,true);
request.getRequestDispatcher("/masterDataQueryScreen.jsp").forward(request, response);
**strong text**session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
**strong text**response.sendRedirect("/masterDataQueryScreen.jsp");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</code></pre> | 25,287,195 | 3 | 0 | null | 2014-08-13 13:01:34.793 UTC | 3 | 2016-09-10 19:40:10.123 UTC | 2015-06-09 12:49:12.84 UTC | user3022012 | null | null | 3,628,691 | null | 1 | 10 | javascript|jsp | 128,496 | <p>So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.</p>
<p>In test.jsp</p>
<p>Create a javascript</p>
<pre><code><script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
</code></pre>
<p>and than at the bottom</p>
<pre><code><script type="text/javascript"> window.onload = alertName; </script>
</code></pre>
<p>Note:im not sure how to type the code in stackoverflow!.
Edit: I just learned how to</p>
<p>Edit 2:
TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect. </p>
<p>To do that i would highly recommendation to use session!</p>
<p>So what you want to do is in your servlet:</p>
<pre><code>session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
</code></pre>
<p>than in the test.jsp</p>
<pre><code><%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
</code></pre>
<p>and than at the bottom</p>
<pre><code><script type="text/javascript"> window.onload = alertName; </script>
</code></pre>
<p>So everytime you submit that form a session will be pass on! If session is not null the function will run!</p> |
45,512,546 | Failed to construct 'File': Iterator getter is not callable in chrome 60 when use JSON.stringify() | <p>System Configuration : macOS Sierra 10.12.5 ; chrome 60; </p>
<p>I am trying to download JSON data ( response object ) as a json file but when I tried to achive this using browser File() object , it gives error</p>
<p><code>Failed to construct 'File': Iterator getter is not callable.</code></p>
<p>below is my code</p>
<pre><code>//`inputData` is the valid response getting from $http.get
var stringifyData = JSON.stringify(inputData);
console.log("stringifyData ", stringifyData);
var file = new File(blob, "filename.json", {type: "text/json;charset=utf-8"});
console.log("file", file);
</code></pre>
<p>what is the issue and why I am getting this error. when I use <code>JSON.stringify(inputData, undefined, 4);</code> then it gives no error and displays proper object in the console.</p> | 45,739,408 | 2 | 0 | null | 2017-08-04 17:33:17.917 UTC | 2 | 2019-04-09 05:47:21.92 UTC | 2018-07-18 12:16:41.04 UTC | null | 1,092,711 | null | 155,861 | null | 1 | 36 | javascript|fileapi | 45,718 | <p>In your case <code>File</code> constructor signature is incorrect, the first argument must be:</p>
<blockquote>
<p>An Array of ArrayBuffer, ArrayBufferView, Blob, or DOMString objects — or a mix of any such objects. This is the file content encoded as UTF-8.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/File/File#Parameters" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/File/File#Parameters</a></p>
</blockquote>
<pre><code>new File([blob], "filename.json", {type: "text/json;charset=utf-8"});
</code></pre> |
5,873,636 | How to enable data binding in KnockoutJS using the ASP.NET MVC 3 "Razor" View Engine? | <p>I'm trying to implement <a href="http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/">this Knockout example</a> using ASP MVC 3's "Razor" view engine.</p>
<p>The first topic covers simple data binding of a C# array using the standard ASP view engine. I am trying the sample example using "Razor", and this line:</p>
<pre><code><script type="text/javascript">
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
</script>
</code></pre>
<p>results in an empty variable for <em>initialData</em>.</p>
<p>I also tried this:</p>
<pre><code>@{
string data = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
</code></pre>
<p>And then specified the initialData like this:</p>
<pre><code>var initialData = @Html.Raw(data);
</code></pre>
<p>This populates <em>initialData</em> with the dataset, but binding does not work. </p>
<p>I'm just trying to databind this set in order to display a count of the ideas, as in the example:</p>
<pre><code><p>You have asked for <span data-bind="text: gifts().length">&nbsp;</span> gift(s)</p>
</code></pre>
<p>Why isn't data binding working in this instance? </p> | 5,875,129 | 2 | 0 | null | 2011-05-03 17:57:13.693 UTC | 10 | 2012-09-18 21:14:54.69 UTC | 2011-05-03 18:14:57.433 UTC | null | 675,285 | null | 675,285 | null | 1 | 16 | asp.net-mvc-3|razor|knockout.js | 9,893 | <p>The easiest way in MVC3 is to do:</p>
<pre><code>var initialData = @Html.Raw(Json.Encode(Model));
</code></pre> |
5,883,282 | Binding property to control in Winforms | <p>What is the best way to bind a property to a control so that when the property value is changed, the control's bound property changes with it.</p>
<p>So if I have a property <code>FirstName</code> which I want to bind to a textbox's <code>txtFirstName</code> text value. So if I change <code>FirstName</code> to value "Stack" then the property <code>txtFirstName.Text</code> also changes to value "Stack".</p>
<p>I know this may sound a stupid question but I'll appreciate the help.</p> | 5,883,321 | 2 | 0 | null | 2011-05-04 12:22:37.307 UTC | 20 | 2018-06-27 20:00:16.97 UTC | 2016-07-17 15:54:00.603 UTC | null | 5,411,172 | null | 573,686 | null | 1 | 50 | c#|vb.net|winforms|binding | 60,826 | <p>You must implement <code>INotifyPropertyChanged</code> And add binding to textbox.</p>
<p>I will provide C# code snippet. Hope it helps</p>
<pre><code>class Sample : INotifyPropertyChanged
{
private string firstName;
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
InvokePropertyChanged(new PropertyChangedEventArgs("FirstName"));
}
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
#endregion
}
</code></pre>
<p>Usage :</p>
<pre><code> Sample sourceObject = new Sample();
textbox.DataBindings.Add("Text",sourceObject,"FirstName");
sourceObject.FirstName = "Stack";
</code></pre> |
60,360,368 | Android 11 (R) file path access | <p>According to the docs file path access is granted in Android R:</p>
<blockquote>
<p>Starting in Android 11, apps that have the READ_EXTERNAL_STORAGE permission can read a device's media files using direct file paths and native libraries. This new capability allows your app to work more smoothly with third-party media libraries.</p>
</blockquote>
<p>The problem is that I can't get the file path from <code>MediaStore</code>, so how are we supposed to read a file path that we can't access/retrieve? Is there a way, I'm not aware of, that we can get the file path from <code>MediaStore</code>?</p>
<hr>
<p>Furthermore, <a href="https://developer.android.com/preview/privacy/storage#all-files-access" rel="noreferrer">the docs say the following</a>:</p>
<blockquote>
<p><strong>All Files Access</strong></p>
<p>Some apps have a core use case that requires broad file access, such as file management or backup & restore operations. They can get All Files Access by doing the following:</p>
<ol>
<li>Declare the MANAGE_EXTERNAL_STORAGE permission.</li>
<li>Direct users to a system settings page where they can enable the Allow access to manage all files option for your app.</li>
</ol>
<p>This permission grants the following:</p>
<ul>
<li>Read access and write access to all files within shared storage.</li>
<li>Access to the contents of the MediaStore.Files table.</li>
</ul>
</blockquote>
<p>But I do not need all file access, I only want the user to select a video from <code>MediaStore</code> and pass the file path to <code>FFmpeg</code>(it requires a file path). I know that I can no longer use the <code>_data</code> column to retrieve a file path.</p>
<hr>
<p>Please note:</p>
<ul>
<li>I know a <code>Uri</code> is returned from <code>MediaStore</code> and does not point to a file.</li>
<li>I know that I can copy the file to my application directory and pass that to <code>FFmpeg</code>, but I could do that before Android R.</li>
<li>I can not pass <code>FileDescriptor</code> to <code>FFmpeg</code> and I can not use <code>/proc/self/fd/</code> (I get <code>/proc/7828/fd/70: Permission denied</code> when selecting a file from the SD Card), have a look at <a href="https://github.com/tanersener/mobile-ffmpeg/issues/334" rel="noreferrer">this issue</a>.</li>
</ul>
<hr>
<p>So what am I supposed to do, am I missing something? What was meant with <code>can read a device's media files using direct file paths and native libraries</code>?</p> | 60,917,774 | 3 | 0 | null | 2020-02-23 08:20:53.003 UTC | 12 | 2021-10-22 09:42:41.397 UTC | 2020-02-24 04:15:47.003 UTC | null | 5,550,161 | null | 5,550,161 | null | 1 | 24 | android|android-11 | 33,449 | <p>After asking a question on <a href="https://issuetracker.google.com/issues/151407044" rel="noreferrer">issuetracker</a>, I've come to the following conclusions:</p>
<ul>
<li>On Android R, the <code>File</code> restrictions that were added in Android Q is removed. So we can once again access <code>File</code> objects.</li>
<li><p>If you are targeting Android 10 > and you want to access/use file paths, you will have to add/keep the following in your manifest:</p>
<pre><code>android:requestLegacyExternalStorage="true"
</code></pre>
<p>This is to ensure that file paths are working on Android 10(Q). On Android R this attribute will be ignored.</p></li>
<li><p>Don't use DATA column for inserting or updating into Media Store, use <code>DISPLAY_NAME</code> and <code>RELATIVE_PATH</code>, here is an example:</p>
<pre class="lang-java prettyprint-override"><code>ContentValues valuesvideos;
valuesvideos = new ContentValues();
valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "YourFolder");
valuesvideos.put(MediaStore.Video.Media.TITLE, "SomeName");
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, "SomeName");
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 1);
ContentResolver resolver = getContentResolver();
Uri collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri uriSavedVideo = resolver.insert(collection, valuesvideos);
</code></pre></li>
<li><p>You can no longer use the <code>ACTION_OPEN_DOCUMENT_TREE</code> or the <code>ACTION_OPEN_DOCUMENT</code> intent action to request that the user select individual files from <code>Android/data/</code>,<code>Android/obb/</code>and all sub-directories.</p></li>
<li>It is recommended to only use <code>File</code> objects when you need to perform "seeking", like when using <code>FFmpeg</code>, for example.</li>
<li>You can only use the data column to access files that are on the disk. You should handle I/O Exceptions accordingly.</li>
</ul>
<hr>
<p>If you want to access a <code>File</code> or want a file path from a <code>Uri</code> that was returned from <code>MediaStore</code>, <a href="https://github.com/HBiSoft/PickiT" rel="noreferrer">I've created a library</a> that handles all the exceptions you might get. This includes all files on the disk, internal and removable disk. When selecting a <code>File</code> from Dropbox, for example, the <code>File</code> will be copied to your applications directory where you have full access, the copied file path will then be returned.</p> |
19,657,852 | pgAdmin III Why query results are shortened? | <p>I've recently installed pgAdmin III 1.18.1 and noticed a strange thing:</p>
<p>Long json query results are shortened to 256 symbols and then ' (...)' is added.</p>
<p>Could someone help me disable this shortening?</p> | 19,853,585 | 2 | 0 | null | 2013-10-29 12:09:34.113 UTC | 4 | 2021-09-26 12:50:57.67 UTC | 2016-06-23 01:08:51.433 UTC | null | 939,860 | null | 1,436,644 | null | 1 | 35 | postgresql|pgadmin | 11,149 | <p>Thanks to user <a href="https://dba.stackexchange.com/users/3684/erwin-brandstetter">Erwin Brandstetter</a> for his answer on <a href="https://dba.stackexchange.com/questions/52399/why-are-query-results-shortened-in-pgadmin-1-18-1">Database Administrators</a>.</p>
<blockquote>
<p>There is a setting for that in the options: Max characters per column - useful when dealing with big columns. Obviously your setting is 256 characters.</p>
<p><img src="https://i.stack.imgur.com/AhlqK.jpg" alt="pgadmin maxcharacter property" /></p>
<p>Set it higher or set it to -1 to disable the feature.</p>
</blockquote> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.